#!/usr/bin/env bash
# 🚀 DEPLOY VECTOR TILES TO VPS
# Uploads generated .pbf tiles to the production server.
# Also updates Caddy config if needed.

set -euo pipefail

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

# Configuration
VPS_HOST="vps-4d8abcb7.vps.ovh.net"
VPS_USER="myroadtrip"
DEST_DIR="/srv/myroadtrip/tiles/pois"
LOCAL_DIR="public/tiles"
LOCAL_CADDYFILE="$SCRIPT_DIR/vps/Caddyfile"

echo "============================================="
echo "🌍 DEPLOYING MAP TILES TO VPS"
echo "============================================="

# 1. Check local tiles
if [ ! -d "$LOCAL_DIR" ]; then
    echo "❌ Error: Local tiles directory '$LOCAL_DIR' not found."
    echo "   Run the tiles generation step first."
    exit 1
fi

TILE_COUNT=$(find "$LOCAL_DIR" -name "*.pbf" | wc -l | tr -d ' ')
echo "📦 Found $TILE_COUNT tile files in $LOCAL_DIR"

if [ "$TILE_COUNT" -eq 0 ]; then
    echo "❌ Error: No .pbf tiles found in '$LOCAL_DIR'."
    exit 1
fi

# 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."
    echo "   Make sure you have SSH access configured for ${VPS_HOST}"
    exit 1
fi
echo "✅ SSH connection OK"

# 3. Update Caddyfile if local version differs
echo "📝 Checking Caddy configuration..."
if [ -f "$LOCAL_CADDYFILE" ]; then
    REMOTE_CADDY_HASH=$(ssh ${VPS_HOST} "md5sum /etc/caddy/Caddyfile 2>/dev/null | cut -d' ' -f1" || echo "none")
    LOCAL_CADDY_HASH=$(md5 -q "$LOCAL_CADDYFILE" 2>/dev/null || md5sum "$LOCAL_CADDYFILE" | cut -d' ' -f1)
    
    if [ "$REMOTE_CADDY_HASH" != "$LOCAL_CADDY_HASH" ]; then
        echo "   ⚠️  Caddyfile differs, updating..."
        scp "$LOCAL_CADDYFILE" "${VPS_HOST}:/tmp/Caddyfile.new"
        ssh ${VPS_HOST} "sudo mv /tmp/Caddyfile.new /etc/caddy/Caddyfile && sudo caddy fmt --overwrite /etc/caddy/Caddyfile"
        echo "   ✅ Caddyfile updated"
    else
        echo "   ✅ Caddyfile already up to date"
    fi
else
    echo "   ⚠️  No local Caddyfile found at $LOCAL_CADDYFILE"
fi

# 4. Create remote directory (if needed)
echo "🔧 Ensuring remote directory exists..."
ssh ${VPS_HOST} "sudo mkdir -p ${DEST_DIR} && sudo chown -R ${VPS_USER}:${VPS_USER} ${DEST_DIR}"

# 5. Rsync upload
echo "🚀 Uploading tiles (Rsync)..."
rsync -avz --delete --progress "$LOCAL_DIR/" "${VPS_HOST}:${DEST_DIR}/"

echo "✅ Upload complete."

# 6. Set permissions for Caddy
echo "🔒 Setting permissions..."
ssh ${VPS_HOST} "sudo chown -R www-data:www-data ${DEST_DIR} && sudo chmod -R 755 ${DEST_DIR}"

# 7. Reload Caddy
echo "🔄 Reloading Caddy..."
ssh ${VPS_HOST} "sudo systemctl reload caddy"

echo ""
echo "✅ Deployment finished!"
echo "   Tiles available at: https://tiles.roadtripper.io/{z}/{x}/{y}.pbf"
echo ""
echo "   To test: curl -I https://tiles.roadtripper.io/0/0/0.pbf"
