#!/bin/bash
# ─────────────────────────────────────────────────────────────
# deploy-platform-to-server.sh
# Run from the VM (backup server) to push the latest platform
# version to a remote server (e.g. main server after failure).
# Usage:
#   ./deploy-platform-to-server.sh                        # deploys to default main server
#   ./deploy-platform-to-server.sh 192.168.1.50           # deploys to custom IP
#   ./deploy-platform-to-server.sh 192.168.1.50 2222      # custom IP + SSH port
# ─────────────────────────────────────────────────────────────

LOCAL_BACKUP_DIR="/backups/platform"
DEPLOY_DIR="/root/management-platform"
LOG="/root/deploy-to-server.log"

# ── Target server (override via args) ────────────────────────
TARGET_IP="${1:-173.249.20.244}"
TARGET_PORT="${2:-22}"
TARGET_USER="root"
SSH_KEY="/root/.ssh/contabo-key"   # adjust if different on VM

SSH_OPTS="-o StrictHostKeyChecking=no -o ConnectTimeout=15 -p $TARGET_PORT -i $SSH_KEY"
SCP_OPTS="-o StrictHostKeyChecking=no -o ConnectTimeout=15 -P $TARGET_PORT -i $SSH_KEY"

log() { echo "$(date '+%Y-%m-%d %H:%M:%S') $1" | tee -a "$LOG"; }

log "════════════════════════════════════════════════"
log "🚀 Deploy platform → $TARGET_USER@$TARGET_IP:$TARGET_PORT"
log "════════════════════════════════════════════════"

# ── Find latest local platform backup ────────────────────────
LATEST=$(ls -t "$LOCAL_BACKUP_DIR"/platform-backup-*.tar.gz 2>/dev/null | head -1)

if [ -z "$LATEST" ]; then
    log "❌ No local platform backups found in $LOCAL_BACKUP_DIR"
    log "   Run pull-platform-backup.sh first"
    exit 1
fi

BACKUP_NAME=$(basename "$LATEST")
log "📦 Using backup: $BACKUP_NAME"

# ── Test SSH connection ───────────────────────────────────────
log "🔗 Testing SSH connection to $TARGET_IP:$TARGET_PORT ..."
ssh $SSH_OPTS $TARGET_USER@$TARGET_IP "echo ok" > /dev/null 2>&1
if [ $? -ne 0 ]; then
    log "❌ Cannot connect to $TARGET_IP:$TARGET_PORT"
    log "   Check: SSH key at $SSH_KEY, server is up, port is correct"
    exit 1
fi
log "✅ SSH connection OK"

# ── Extract backup locally to get the platform files ─────────
EXTRACT_DIR=$(mktemp -d /tmp/deploy-to-server-XXXXXX)
log "📂 Extracting backup locally..."
tar -xzf "$LATEST" -C "$EXTRACT_DIR"

if [ $? -ne 0 ]; then
    log "❌ Extraction failed — backup may be corrupt"
    rm -rf "$EXTRACT_DIR"
    exit 1
fi

PLATFORM_SRC=$(find "$EXTRACT_DIR" -maxdepth 3 -type d -name "management-platform" | head -1)

if [ -z "$PLATFORM_SRC" ] || [ ! -f "$PLATFORM_SRC/app.py" ]; then
    log "❌ Could not find valid management-platform/app.py in archive"
    rm -rf "$EXTRACT_DIR"
    exit 1
fi

log "✅ Platform source found: $PLATFORM_SRC"

# ── Stop the service on remote if running ────────────────────
log "🛑 Stopping service on remote (if running)..."
ssh $SSH_OPTS $TARGET_USER@$TARGET_IP \
    "systemctl stop management-platform 2>/dev/null ; pkill -f 'flask\|app.py' 2>/dev/null ; echo stopped"

# ── Backup current version on remote ─────────────────────────
log "📦 Archiving current version on remote..."
ssh $SSH_OPTS $TARGET_USER@$TARGET_IP \
    "if [ -d /root/management-platform ] && [ \"\$(ls -A /root/management-platform 2>/dev/null)\" ]; then
        mkdir -p /backups/platform/old-deploys
        tar -czf /backups/platform/old-deploys/management-platform.old.\$(date +%Y%m%d_%H%M%S).tar.gz \
            -C /root management-platform 2>/dev/null
        rm -rf /root/management-platform
        ls -t /backups/platform/old-deploys/management-platform.old.*.tar.gz 2>/dev/null \
            | tail -n +3 | xargs rm -f 2>/dev/null
        echo 'archived'
    else
        echo 'nothing to archive'
    fi"

# ── Copy platform files to remote ────────────────────────────
log "📤 Copying platform files to $TARGET_IP ..."
scp $SCP_OPTS -r "$PLATFORM_SRC" $TARGET_USER@$TARGET_IP:/root/management-platform

if [ $? -ne 0 ]; then
    log "❌ SCP failed"
    rm -rf "$EXTRACT_DIR"
    exit 1
fi

log "✅ Files copied"

# ── Fix permissions and venv on remote ───────────────────────
log "🔧 Fixing permissions and venv on remote..."
ssh $SSH_OPTS $TARGET_USER@$TARGET_IP "
    chmod +x /root/management-platform/*.sh 2>/dev/null
    chmod +x /root/management-platform/*.py 2>/dev/null
    cd /root/management-platform
    if [ ! -d venv ]; then
        echo '🐍 Creating venv...'
        python3 -m venv venv
        source venv/bin/activate
        pip install flask --quiet
        deactivate
    else
        echo '🐍 Venv exists'
    fi
"

# ── Start service on remote ───────────────────────────────────
log "▶️  Starting management-platform on remote..."
ssh $SSH_OPTS $TARGET_USER@$TARGET_IP "systemctl start management-platform"

sleep 4

STATUS=$(ssh $SSH_OPTS $TARGET_USER@$TARGET_IP "systemctl is-active management-platform 2>/dev/null")

if [ "$STATUS" = "active" ]; then
    log "✅ Service is running on $TARGET_IP"
    log "🌐 Access at: http://$TARGET_IP:5000"
else
    log "⚠️  Service may not be running (status: $STATUS)"
    log "   Check on remote: journalctl -u management-platform -n 30"
fi

# ── Cleanup ───────────────────────────────────────────────────
rm -rf "$EXTRACT_DIR"
log "🎉 Done — platform deployed to $TARGET_IP from backup: $BACKUP_NAME"
