#!/usr/bin/env bash
# ---------------------------------------------------------------
# Laptop-side deploy script. Rsyncs the repo to the VPS and
# triggers a rebuild. Assumes provision.sh has already been run
# on the server.
#
# Usage (from the `site/` directory on your laptop):
#   DEPLOY_HOST=158.220.127.51 deploy/scripts/deploy.sh
#   # or set in .env.deploy.local (gitignored)
#
# Options:
#   DEPLOY_HOST    — the server IP or hostname (required)
#   DEPLOY_USER    — SSH user, default "deploy"
#   APP_HOME       — where to rsync to, default /home/$DEPLOY_USER/orthoglobe
# ---------------------------------------------------------------
set -euo pipefail

if [[ -f .env.deploy.local ]]; then
  # shellcheck disable=SC1091
  source .env.deploy.local
fi

DEPLOY_HOST="${DEPLOY_HOST:?DEPLOY_HOST not set. Export it or put it in .env.deploy.local.}"
DEPLOY_USER="${DEPLOY_USER:-deploy}"
APP_HOME="${APP_HOME:-/home/$DEPLOY_USER/orthoglobe}"
SSH_TARGET="$DEPLOY_USER@$DEPLOY_HOST"

echo ">>> Deploying to $SSH_TARGET:$APP_HOME"

# Rsync everything except node_modules, .next, .env*, legacy dumps, git.
rsync -az --delete --info=stats2 \
  --exclude=.git \
  --exclude=node_modules \
  --exclude=.next \
  --exclude=.pnpm-store \
  --exclude=.env \
  --exclude=.env.local \
  --exclude=.env.deploy.local \
  --exclude=wp-migration-report-*.json \
  --exclude=/legacy \
  --exclude=.playwright-mcp \
  --exclude=test-results \
  --exclude=playwright-report \
  --exclude=coverage \
  ./ "$SSH_TARGET:$APP_HOME/"

echo ">>> Rebuilding + restarting containers on the server..."
ssh "$SSH_TARGET" "bash -s" <<EOF
set -euo pipefail
cd $APP_HOME
if [[ ! -f .env ]]; then
  echo ".env missing on server — copy deploy/.env.production.example and fill it in first." >&2
  exit 1
fi
docker compose -f docker-compose.production.yml pull postgres caddy
docker compose -f docker-compose.production.yml up -d --build
# Prune dangling images after a successful deploy to save disk.
docker image prune -f
echo ">>> Status:"
docker compose -f docker-compose.production.yml ps
EOF

echo ""
echo ">>> Deploy complete — tail logs with:"
echo "   ssh $SSH_TARGET 'docker compose -f $APP_HOME/docker-compose.production.yml logs -f --tail 200'"
