#!/usr/bin/env bash
# Deploy the Docker Compose production stack from the repo root.
# Prerequisites: `.env` (from `.env.example`) on the SAME host/path as this repo.
#
# Usage:
#   ./scripts/deploy-prod.sh              # pull pinned images, build, up -d
#   ./scripts/deploy-prod.sh --no-pull    # offline / cached images only
#fdf
set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
COMPOSE_ABS="${ROOT}/docker-compose.prod.yml"

cd "$ROOT"

DO_PULL=1
while [[ $# -gt 0 ]]; do
  case "$1" in
    --no-pull) DO_PULL=0 ;;
    -h|--help)
      grep -E '^#( |$)' "$0" | sed 's/^# \{0,1\}//'
      exit 0
      ;;
    *)
      printf 'Unknown argument: %s\n' "$1" >&2
      exit 1
      ;;
  esac
  shift
done

if [[ ! -f "$ROOT/.env" ]]; then
  printf 'Missing %s\nRun: cp .env.example .env && edit secrets\n' "$ROOT/.env" >&2
  exit 1
fi

echo "→ Validating prod environment..."
"$ROOT/scripts/verify-prod-env.sh"

echo "→ Validating compose file..."
docker compose --env-file "$ROOT/.env" -f "$COMPOSE_ABS" config >/dev/null

if [[ "$DO_PULL" -eq 1 ]]; then
  echo "→ Pulling images..."
  docker compose --env-file "$ROOT/.env" -f "$COMPOSE_ABS" pull
fi

echo "→ Building images..."
docker compose --env-file "$ROOT/.env" -f "$COMPOSE_ABS" build

echo "→ Starting stack..."
docker compose --env-file "$ROOT/.env" -f "$COMPOSE_ABS" up -d --remove-orphans

echo "→ Status"
docker compose --env-file "$ROOT/.env" -f "$COMPOSE_ABS" ps

printf '\nDeployed. Logs: docker compose --env-file .env -f docker-compose.prod.yml logs -f be0\n'
printf 'Connectivity:  bash scripts/check-prod-stack.sh\n'
printf 'Postgres auth is FIXED on first DB init — docs/deploy-production-docker.md\n'
