#!/usr/bin/env bash
# Alterra Estates — deploy or update on the VPS (run from the repository folder as the deploy user).
#   ./deploy/deploy.sh                 # production (deploy/.env.production)
#   ENV=staging ./deploy/deploy.sh     # staging    (deploy/.env.staging)
set -euo pipefail
cd "$(dirname "$0")/.."

ENV="${ENV:-production}"
ENV_FILE="deploy/.env.$ENV"
[[ -f "$ENV_FILE" ]] || { echo "Missing $ENV_FILE (copy it from $ENV_FILE.example)." >&2; exit 1; }
compose() { docker compose --env-file "$ENV_FILE" "$@"; }

echo "==> Updating code"
git pull --ff-only

echo "==> Backup before deploying (skipped on the first deploy)"
if compose ps --status running api 2>/dev/null | grep -q api; then
  if ! compose exec -T api npm run db:backup; then
    echo "    Backup failed — continuing is risky; press Ctrl+C within 10 s to stop."
    sleep 10
  fi
fi

echo "==> Building and starting (migrations run automatically when the API starts)"
compose up -d --build --remove-orphans

echo "==> Waiting for the site to answer"
for _ in $(seq 1 30); do
  if compose exec -T web wget -qO- http://127.0.0.1:3000/healthz >/dev/null 2>&1; then
    compose exec -T web wget -qO- http://127.0.0.1:3000/healthz; echo
    break
  fi
  sleep 5
done

echo "==> Daily backup at 03:30 (cron, installed once)"
CRON_LINE="30 3 * * * cd $(pwd) && docker compose --env-file $ENV_FILE exec -T api npm run db:backup >> \$HOME/alterra-backup.log 2>&1"
( crontab -l 2>/dev/null | grep -Fv "npm run db:backup" ; echo "$CRON_LINE" ) | crontab -

echo "==> Cleaning old images"
docker image prune -f >/dev/null

echo "Deployed ($ENV)."
