#!/usr/bin/env bash
set -Eeuo pipefail

# Production update script for Docker Compose Laravel deployments.
# Usage from the production server, at the project root:
#   COMPOSE_FILE=docker-compose.yml APP_SERVICE=app DB_SERVICE=mysql DB_NAME=life_analytics DB_USER=laravel DB_PASSWORD=secret scripts/update-prod.sh
# Optional:
#   BRANCH=main BUILD_ASSETS=1 scripts/update-prod.sh

COMPOSE_FILE="${COMPOSE_FILE:-docker-compose.yml}"
APP_SERVICE="${APP_SERVICE:-app}"
DB_SERVICE="${DB_SERVICE:-mysql}"
DB_NAME="${DB_NAME:-life_analytics}"
DB_USER="${DB_USER:-laravel}"
DB_PASSWORD="${DB_PASSWORD:-secret}"
BRANCH="${BRANCH:-main}"
BUILD_ASSETS="${BUILD_ASSETS:-0}"
BACKUP_DIR="${BACKUP_DIR:-backups}"
TIMESTAMP="$(date +%Y%m%d_%H%M%S)"
BACKUP_FILE="${BACKUP_DIR}/${DB_NAME}_${TIMESTAMP}.sql.gz"

compose() {
    docker compose -f "${COMPOSE_FILE}" "$@"
}

if [ ! -f "${COMPOSE_FILE}" ]; then
    echo "Missing compose file: ${COMPOSE_FILE}" >&2
    exit 1
fi

mkdir -p "${BACKUP_DIR}"

echo "[1/9] Enabling maintenance mode"
compose exec -T "${APP_SERVICE}" php artisan down --render="errors::503" || true

cleanup() {
    echo "[cleanup] Disabling maintenance mode"
    compose exec -T "${APP_SERVICE}" php artisan up || true
}
trap cleanup EXIT

echo "[2/9] Backing up database to ${BACKUP_FILE}"
compose exec -T "${DB_SERVICE}" sh -c "mysqldump -u'${DB_USER}' -p'${DB_PASSWORD}' --single-transaction --quick --routines --triggers '${DB_NAME}'" | gzip > "${BACKUP_FILE}"

echo "[3/9] Pulling latest code from ${BRANCH}"
git fetch --all --prune
git checkout "${BRANCH}"
git pull --ff-only origin "${BRANCH}"

echo "[4/9] Rebuilding/restarting containers"
compose up -d --build

echo "[5/9] Installing PHP dependencies"
compose exec -T "${APP_SERVICE}" composer install --no-dev --prefer-dist --optimize-autoloader --no-interaction

if [ "${BUILD_ASSETS}" = "1" ]; then
    echo "[6/9] Building frontend assets on host"
    npm ci
    npm run build
else
    echo "[6/9] Skipping frontend build (set BUILD_ASSETS=1 to enable)"
fi

echo "[7/9] Running database migrations"
compose exec -T "${APP_SERVICE}" php artisan migrate --force

echo "[8/9] Clearing and warming Laravel caches"
compose exec -T "${APP_SERVICE}" php artisan optimize:clear
compose exec -T "${APP_SERVICE}" php artisan config:cache
compose exec -T "${APP_SERVICE}" php artisan route:cache
compose exec -T "${APP_SERVICE}" php artisan view:cache

echo "[9/9] Final migration status"
compose exec -T "${APP_SERVICE}" php artisan migrate:status | tail -20

echo "Production update completed. DB backup: ${BACKUP_FILE}"
