#!/usr/bin/env bash
# Runs on the target VM after a candidate Caddyfile has been uploaded.
set -Eeuo pipefail

CANDIDATE="${1:?candidate Caddyfile is required}"
APP_DIR="${2:?application directory is required}"
TARGET="/etc/caddy/Caddyfile"

[[ -f "$CANDIDATE" ]] || { echo "candidate Caddyfile not found: $CANDIDATE" >&2; exit 1; }
command -v caddy >/dev/null 2>&1 || { echo "caddy is not installed" >&2; exit 1; }
command -v systemctl >/dev/null 2>&1 || { echo "systemctl is not installed" >&2; exit 1; }
sudo -n true || { echo "passwordless sudo is required for Caddy configuration" >&2; exit 1; }
sudo test -f "$TARGET" || { echo "existing $TARGET not found; install the official Caddy package first" >&2; exit 1; }

BACKUP_DIR="$APP_DIR/caddy-backups"
mkdir -p "$BACKUP_DIR"
BACKUP="$BACKUP_DIR/Caddyfile.$(date -u +%Y%m%dT%H%M%SZ)"
sudo cat "$TARGET" > "$BACKUP"
chmod 600 "$BACKUP"

was_active="N"
if sudo systemctl is-active --quiet caddy; then
  was_active="Y"
fi

rollback() {
  status=$?
  trap - ERR
  echo "Caddy 적용 실패, 이전 설정 복원: $BACKUP" >&2
  sudo install -o root -g root -m 644 "$BACKUP" "$TARGET"
  if [[ "$was_active" == "Y" ]]; then
    sudo systemctl reload caddy || true
  else
    sudo systemctl stop caddy || true
  fi
  exit "$status"
}
trap rollback ERR

sudo caddy validate --config "$CANDIDATE" --adapter caddyfile
sudo install -o root -g root -m 644 "$CANDIDATE" "$TARGET"

if [[ "$was_active" == "Y" ]]; then
  sudo systemctl reload caddy
else
  sudo systemctl enable --now caddy
fi

sudo systemctl is-active --quiet caddy
sudo systemctl is-enabled --quiet caddy
trap - ERR

printf 'caddy active; backup=%s\n' "$BACKUP"
