#!/usr/bin/env bash
# 🔧 DEPLOY CADDY CONFIG TO VPS
# Updates the Caddyfile on the VPS and reloads Caddy.

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Configuration
VPS_HOST="vps-4d8abcb7.vps.ovh.net"
LOCAL_CADDYFILE="$SCRIPT_DIR/vps/Caddyfile"

echo "============================================="
echo "🔧 DEPLOYING CADDY CONFIG TO VPS"
echo "============================================="

# 1. Check local Caddyfile
if [ ! -f "$LOCAL_CADDYFILE" ]; then
    echo "❌ Error: Local Caddyfile not found at $LOCAL_CADDYFILE"
    exit 1
fi
echo "📄 Local Caddyfile: $LOCAL_CADDYFILE"

# 2. Test SSH connectivity
echo "🔗 Testing SSH connection..."
if ! ssh -o BatchMode=yes -o ConnectTimeout=10 ${VPS_HOST} "echo ok" > /dev/null 2>&1; then
    echo "❌ Error: Cannot connect to VPS via SSH."
    exit 1
fi
echo "✅ SSH connection OK"

# 3. Backup existing config
echo "📦 Backing up existing Caddyfile..."
ssh ${VPS_HOST} "sudo cp /etc/caddy/Caddyfile /etc/caddy/Caddyfile.backup.$(date +%Y%m%d_%H%M%S)"

# 4. Upload new config
echo "📤 Uploading new Caddyfile..."
scp "$LOCAL_CADDYFILE" "${VPS_HOST}:/tmp/Caddyfile.new"

# 5. Validate config
echo "🔍 Validating Caddy config..."
if ! ssh ${VPS_HOST} "sudo caddy validate --config /tmp/Caddyfile.new"; then
    echo "❌ Error: Invalid Caddy configuration!"
    echo "   The config was NOT applied. Fix the errors and try again."
    exit 1
fi
echo "✅ Config is valid"

# 6. Apply config
echo "📝 Applying new config..."
ssh ${VPS_HOST} "sudo mv /tmp/Caddyfile.new /etc/caddy/Caddyfile"

# 7. Format and reload
echo "🔄 Reloading Caddy..."
ssh ${VPS_HOST} "sudo caddy fmt --overwrite /etc/caddy/Caddyfile && sudo systemctl reload caddy"

echo ""
echo "✅ Caddy config deployed successfully!"
echo ""
echo "   Test tiles endpoint:"
echo "   curl -I https://tiles.roadtripper.io/"
