#!/usr/bin/env bash
# Replace the manually-deployed /var/www/html/account with a real git
# checkout so future deploys are `git pull`. Preserves .env + storage/.
set -e

cd /var/www/html

if [ ! -d account ]; then
  echo "ERROR: /var/www/html/account does not exist"
  exit 1
fi
if [ -d account/.git ]; then
  echo "account/ is already a git checkout — nothing to do."
  exit 0
fi

# Probe the deploy key works against the repo BEFORE touching anything.
echo "=== Probe deploy key ==="
GIT_SSH_COMMAND="ssh -i /root/.ssh/account_deploy -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new" \
  git ls-remote git@github.com:2ppaamm/account.git HEAD 2>&1 | head -3 \
  || (echo "Deploy key not authorised on the repo — add /root/.ssh/account_deploy.pub at https://github.com/2ppaamm/account/settings/keys then re-run."; exit 1)

echo ""
echo "=== Snapshot current state ==="
TS=$(date +%Y%m%d-%H%M%S)
BAK="account.bak-${TS}"
cp -a account "$BAK"
echo "Snapshot: $BAK"

echo ""
echo "=== Clone fresh via the github-account SSH alias ==="
rm -rf account
git clone git@github-account:2ppaamm/account.git account 2>&1 | tail -3

echo ""
echo "=== Restore .env + storage from snapshot ==="
cp "$BAK/.env" account/.env
# storage/ has logs, sessions, framework caches — keep them so we don't
# lose anything. The repo's storage/.gitignore covers most of it anyway.
rsync -a --delete "$BAK/storage/" account/storage/ 2>/dev/null || true
# bootstrap/cache is git-tracked at the empty-marker level but Laravel
# writes runtime caches into it; preserve them.
rsync -a "$BAK/bootstrap/cache/" account/bootstrap/cache/ 2>/dev/null || true

echo ""
echo "=== composer install (no-dev, optimised) ==="
cd account
COMPOSER_ALLOW_SUPERUSER=1 composer install --no-dev --optimize-autoloader --no-interaction --no-progress 2>&1 | tail -5

echo ""
echo "=== Perms + cache ==="
chown -R www-data:www-data /var/www/html/account
chmod -R 775 storage bootstrap/cache
php artisan config:cache 2>&1 | tail -1
php artisan route:cache 2>&1 | tail -1
systemctl reload apache2
echo "apache reloaded"

echo ""
echo "=== Verify ==="
curl -s -o /dev/null -w "  account /        https %{http_code}\n" https://account.allgifted.com/
curl -s -o /dev/null -w "  account /login   https %{http_code}\n" https://account.allgifted.com/login
echo ""
echo "=== Git state ==="
git log --oneline -1
echo ""
echo "=== Backup retained at /var/www/html/$BAK ==="
echo "Inspect it and run: rm -rf /var/www/html/$BAK   when you're satisfied."
