#!/usr/bin/env bash
set -euo pipefail

USER="${USER:-$(whoami)}"
HOST="${HOST:-$(hostname -s 2>/dev/null || hostname)}"
DATE="$(date +%F)"
SSH_DIR="$HOME/.ssh"
mkdir -p "$SSH_DIR"
PASS_PATH="personal/ssh/$USER@$HOST/$DATE"

DOTFILES_DIR="$HOME/.dotfiles"
COMMIT_MSG="[ssh] Rekey host $HOST"

# --- Temporary directory for private key (macOS compatible) ---
# Tries /dev/shm if present (Linux), otherwise falls back to standard temp.
if [[ -d /dev/shm && -w /dev/shm ]]; then
  TMPDIR_BASE="/dev/shm"
else
  TMPDIR_BASE="${TMPDIR:-/tmp}"
fi

TMP_WORKDIR="$(mktemp -d "$TMPDIR_BASE/sshkey.${USER}.${HOST}.${DATE}.XXXXXX")"
TMP_PRIV="$TMP_WORKDIR/id_ed25519"

cleanup() {
  # best-effort secure cleanup: delete key material and remove temp dir
  rm -f "$TMP_PRIV" "$TMP_PRIV.pub" 2>/dev/null || true
  rmdir "$TMP_WORKDIR" 2>/dev/null || true
}
trap cleanup EXIT INT TERM

# Generate Ed25519 key pair into temp dir
ssh-keygen -t ed25519 -f "$TMP_PRIV" -N "" -q

# Insert private key into pass
pass insert --multiline --force "$PASS_PATH" < "$TMP_PRIV"
echo "Private key stored in pass at $PASS_PATH"

# Extract public key from the same temp file
ssh-keygen -y -f "$TMP_PRIV" > "$SSH_DIR/$USER@$HOST.pub"
chmod 600 "$SSH_DIR/$USER@$HOST.pub" 2>/dev/null || true
echo "Public key written to $SSH_DIR/$USER@$HOST.pub"

# Temp key removed automatically by trap
cat "$SSH_DIR/$USER@$HOST.pub" >> ~/.ssh/authorized_keys
echo "Public key added to authorized_keys"

# ------------------------------------------------------------------
# Git commit dotfiles changes (ssh + password-store)
# ------------------------------------------------------------------
COMMIT_MSG="[ssh] Rekey host $HOST"

if [[ -d "$DOTFILES_DIR/.git" ]]; then
  pushd "$DOTFILES_DIR" >/dev/null

  # Stage only relevant dirs
  git add ssh password-store 2>/dev/null || true

  if ! git diff --cached --quiet; then
    git commit -m "$COMMIT_MSG"
    git push
    echo "Dotfiles committed & pushed: $COMMIT_MSG"
  else
    echo "No dotfiles changes to commit"
  fi

  popd >/dev/null
else
  echo "Dotfiles repo not found at $DOTFILES_DIR — skipping commit"
fi
