#!/usr/bin/env bash
# Deploy / update the disclosure stack on the VPS.
#
# Steps:
#   1. Ensure VPS_DEPLOY_ROOT exists.
#   2. Upload docker-compose.yml + .env to the VPS.
#   3. Pull images.
#   4. docker compose up -d.
#   5. Print status.
#
# Idempotent: re-run anytime, only changed services restart.

source "$(dirname "$0")/_lib.sh"
set -euo pipefail

STACK_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
COMPOSE_FILE="${STACK_DIR}/docker-compose.yml"
ENV_FILE="${STACK_DIR}/.env"

if [ ! -f "$COMPOSE_FILE" ]; then
  echo "❌ $COMPOSE_FILE not found. The docker-compose.yml hasn't been generated yet — see README."
  exit 1
fi

echo "→ Creating deploy root on VPS: $VPS_DEPLOY_ROOT"
vps_ssh "mkdir -p ${VPS_DEPLOY_ROOT}"

echo ""
echo "→ Uploading docker-compose.yml and .env"
vps_rsync "$COMPOSE_FILE" "${VPS_DEPLOY_ROOT}/docker-compose.yml"
vps_rsync "$ENV_FILE"     "${VPS_DEPLOY_ROOT}/.env"

echo ""
echo "→ Pulling latest images on VPS"
vps_ssh "cd ${VPS_DEPLOY_ROOT} && docker compose pull"

echo ""
echo "→ Bringing stack up (will recreate changed services only)"
vps_ssh "cd ${VPS_DEPLOY_ROOT} && docker compose up -d --remove-orphans"

echo ""
echo "→ Current stack status:"
vps_ssh "cd ${VPS_DEPLOY_ROOT} && docker compose ps"

echo ""
echo "✓ Deploy complete. Logs:  ./scripts/logs.sh <service>"
