#! /bin/bash
set -euo pipefail

# Usage: ./scripts/rebuild-prod.sh [branch]
# Default branch is current; pass a branch to checkout before pulling/building.

COMPOSE_FILE=docker-compose-prod.yml

echo "[1/7] Git: Fetch & pull latest changes"
if [ "${1-}" != "" ]; then
  git fetch origin "$1"
  git checkout "$1"
fi
git pull --rebase

echo "[2/7] Stop and remove running services (including orphans)"
sudo docker compose -f "$COMPOSE_FILE" down --remove-orphans || true

echo "[3/7] Pull base images (e.g., caddy)"
sudo docker compose -f "$COMPOSE_FILE" pull || true

echo "[4/7] Build application image without cache"
sudo docker compose -f "$COMPOSE_FILE" build --no-cache

echo "[5/7] Start services in background"
sudo docker compose -f "$COMPOSE_FILE" up -d

echo "[6/7] Wait for app healthcheck to pass"
# Wait up to ~90s for healthy status using docker inspect (no jq dependency)
for i in {1..18}; do
  # Check health status if available
  HEALTH=$(sudo docker inspect -f '{{if .State.Health}}{{.State.Health.Status}}{{end}}' stargirlnails-app 2>/dev/null || true)
  if [ "$HEALTH" = "healthy" ]; then
    echo "Service is healthy."
    break
  fi

  # Fallback: ensure container is running
  STATE=$(sudo docker inspect -f '{{.State.Status}}' stargirlnails-app 2>/dev/null || true)
  if [ "$STATE" = "running" ] && [ -z "$HEALTH" ]; then
    echo "Service is running (no healthcheck reported)."
    break
  fi

  sleep 5
done

echo "[7/7] Tail recent logs (press Ctrl+C to exit)"
sudo docker compose -f "$COMPOSE_FILE" logs --since=10m -f
