#!/usr/bin/env bash
set -e
cd /var/www/html

echo "=== Restoring account from snapshot ==="
if [ -d account ]; then
  echo "account/ already exists — skipping restore"
else
  BAK=$(ls -d account.bak-* 2>/dev/null | sort | tail -1)
  if [ -z "$BAK" ]; then
    echo "ERROR: no snapshot found"
    exit 1
  fi
  echo "Restoring from $BAK"
  cp -a "$BAK" account
  chown -R www-data:www-data account
fi

echo ""
echo "=== Verify app is back online ==="
systemctl reload apache2
sleep 1
curl -s -o /dev/null -w "  /        → %{http_code}\n" https://account.allgifted.com/
curl -s -o /dev/null -w "  /login   → %{http_code}\n" https://account.allgifted.com/login

echo ""
echo "=== Probe deploy key ==="
echo "Trying github-account alias..."
GIT_SSH_COMMAND="ssh -i /root/.ssh/account_deploy -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new -o BatchMode=yes" \
  git ls-remote git@github.com:2ppaamm/account.git HEAD 2>&1 | head -3
echo ""
echo "Public key (give to user if probe failed):"
cat /root/.ssh/account_deploy.pub
