#!/bin/bash
# =============================================================================
# MOPC Platform - Update / Redeploy Script
# =============================================================================
# Usage: ./scripts/update.sh
# Pulls the latest image from the registry and restarts the app.
# PostgreSQL is NOT restarted.

set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
DOCKER_DIR="$PROJECT_DIR/docker"

echo "============================================"
echo "  MOPC Platform - Update"
echo "============================================"
echo ""

# 1. Pull latest image from registry
echo "==> Pulling latest image..."
cd "$DOCKER_DIR"
docker compose pull app

# 2. Restart app only (postgres stays running)
echo "==> Restarting app..."
docker compose up -d app

# 3. Wait for health check
echo "==> Waiting for application to start..."
MAX_WAIT=120
WAITED=0
while [ $WAITED -lt $MAX_WAIT ]; do
    if curl -sf http://localhost:7600/api/health > /dev/null 2>&1; then
        echo ""
        echo "============================================"
        echo "  Update complete! App is healthy."
        echo "============================================"
        exit 0
    fi
    sleep 2
    WAITED=$((WAITED + 2))
    printf "."
done

echo ""
echo "WARNING: Application did not become healthy within ${MAX_WAIT}s."
echo "Check logs: cd $DOCKER_DIR && docker compose logs -f app"
exit 1
