#!/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)
#
# Git “dubious ownership”: avoid sudo ./deploy.sh — it runs git as root while the clone is
# owned by your user. Prefer: ./deploy.sh as that user (default GIT_PULL_CMD is git pull, no sudo).
# Root-owned checkout only: GIT_PULL_CMD="sudo git pull --ff-only" ./deploy.sh
# Or one-time: git config --global --add safe.directory /path/to/clone
#
# 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"

# Default: same-user git pull (avoids dubious-ownership when repo is not root-owned)
GIT_PULL_CMD="${GIT_PULL_CMD:-git pull --ff-only}"
DOCKER="${DOCKER:-sudo docker compose}"

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."
