#!/bin/bash
# Copy host Tor identity → container data. Works with: sudo ./migrate-identity.sh
set -euo pipefail

if [[ "$(id -u)" -ne 0 ]]; then
  exec sudo -H "$0" "$@"
fi

OWNER="${SUDO_USER:-hernani}"
if [[ "$OWNER" == root ]]; then OWNER=hernani; fi
BASE="$(getent passwd "$OWNER" | cut -d: -f6)/koopa-tor-relay"
SRC=/var/lib/tor
DST="$BASE/data"

if [[ ! -d "$BASE" ]]; then
  echo "ERROR: missing $BASE" >&2
  exit 1
fi
if systemctl is-active --quiet tor 2>/dev/null; then
  echo "ERROR: stop host tor first:  systemctl stop tor" >&2
  exit 1
fi
if command -v podman >/dev/null 2>&1; then
  if runuser -u "$OWNER" -- podman ps --format "{{.Names}}" 2>/dev/null | grep -qx koopa-tor-relay; then
    echo "ERROR: stop container first:  podman stop koopa-tor-relay" >&2
    exit 1
  fi
fi

echo "Copying $SRC → $DST (identity keys as $OWNER)…"
mkdir -p "$DST"
rsync -aHAX --delete "$SRC"/ "$DST"/
chown -R "${OWNER}:${OWNER}" "$DST"
chmod 700 "$DST"

echo "--- fingerprint ---"
[[ -f "$DST/fingerprint" ]] && cat "$DST/fingerprint" || echo "(no fingerprint file yet)"
[[ -f "$DST/fingerprint-ed25519" ]] && cat "$DST/fingerprint-ed25519" || true
echo "OK — $DST ready. Then: podman start koopa-tor-relay"
