#!/usr/bin/env bash
# Deploy: pull latest git, rebuild images, recreate containers, apply SQL migrations.
# Run from the repo root (or anywhere — script cds to its directory).
#
# If you see: sudo: ./deploy.sh: command not found — make it executable: chmod +x deploy.sh
# Prefer running WITHOUT sudo: ./deploy.sh   (the script uses sudo for docker/git only when needed)
# Or: bash deploy.sh   or   sudo bash deploy.sh
#
# Usage:
#   ./deploy.sh                    # build, up, then apply supabase/migrations (tracked in DB)
#   ./deploy.sh migrate            # same as plain ./deploy.sh (kept for backwards compatibility)
#   FULL_REBUILD=1 ./deploy.sh    # docker compose build --no-cache
#   SKIP_MIGRATIONS=1 ./deploy.sh # skip node scripts/apply-sql-migrations.mjs (emergency / CI)
#
# Never use: sudo ./deploy.sh — git runs as root → /root/.ssh → GitHub "Permission denied (publickey)".
# Run ./deploy.sh as the user that owns the clone (Docker still uses sudo via DOCKER below).
# Dubious ownership: git config --global --add safe.directory /path/to/clone
#
# Default: GIT_PULL_CMD=git pull --no-rebase (override e.g. GIT_PULL_CMD="git pull --ff-only").
# Pull fails with ".git/objects" permission errors → sudo chown -R "$(id -un):$(id -gn)" .git
# Root-only deploy with keys in /root/.ssh: DEPLOY_ALLOW_ROOT=1 sudo ./deploy.sh
#
# Windows: use deploy.bat (optional: deploy.bat migrate, or deploy-with-migrate.bat).
#
# The compose stack is stopped (docker compose down) after pull and before build/up so old
# containers do not block port mappings or leave conflicting names. Set SKIP_STACK_STOP=1 to skip.

set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$ROOT"

if find .git/objects -user root 2>/dev/null | head -n1 | grep -q .; then
  echo >&2 "error: .git/objects contains root-owned files (merge/pull cannot write new objects)."
  echo >&2 "Run once:  sudo chown -R \"$(id -un):$(id -gn)\" \"$ROOT/.git\""
  exit 1
fi

GIT_PULL_CMD="${GIT_PULL_CMD:-git pull --no-rebase}"
DOCKER="${DOCKER:-sudo docker compose}"

if [[ "${EUID:-0}" -eq 0 && "${DEPLOY_ALLOW_ROOT:-}" != "1" ]]; then
  echo "ERROR: Do not run this script with sudo." >&2
  echo "  git pull would use root's SSH keys (~/.ssh in /root), not yours → GitHub: Permission denied (publickey)." >&2
  echo "  Run as your normal user:  ./deploy.sh" >&2
  echo "  (Docker commands still run via: ${DOCKER})" >&2
  echo "  If you truly deploy as root with keys only in /root/.ssh:  DEPLOY_ALLOW_ROOT=1 sudo ./deploy.sh" >&2
  exit 1
fi

echo "==> $GIT_PULL_CMD"
eval "$GIT_PULL_CMD"

if [[ "${SKIP_STACK_STOP:-}" != "1" ]]; then
  echo "==> $DOCKER down (stop stack before rebuild)"
  $DOCKER down
else
  echo "==> SKIP_STACK_STOP=1 — leaving existing containers running"
fi

if [[ "${FULL_REBUILD:-}" == "1" ]]; then
  echo "==> $DOCKER build --no-cache"
  $DOCKER build --no-cache
else
  echo "==> $DOCKER build"
  $DOCKER build
fi

echo "==> $DOCKER up -d --build --force-recreate"
$DOCKER up -d --build --force-recreate

echo "==> Status"
$DOCKER ps

# Idempotent migrations (tracks public._wa_sql_migrations); aligns with unified Supabase + app compose stack.
export DOCKER_COMPOSE=${DOCKER_COMPOSE:-$DOCKER}
if command -v node >/dev/null 2>&1; then
  echo "==> SQL migrations (node scripts/apply-sql-migrations.mjs)"
  (cd "$ROOT" && node scripts/apply-sql-migrations.mjs)
else
  echo "WARNING: node not found — install Node.js or run: DOCKER_COMPOSE=\"$DOCKER\" node scripts/apply-sql-migrations.mjs"
fi

echo "==> Done."
