#!/usr/bin/env bash
# Run deployment on ml110
# This script provides instructions and can optionally run the deployment

set -euo pipefail

REMOTE_HOST="192.168.11.10"
REMOTE_USER="root"
REMOTE_PASS="L@kers2010"

echo "=== Complete Validated Deployment on ml110 ==="
echo ""
echo "Target: ${REMOTE_USER}@${REMOTE_HOST}"
echo ""

# Test connection
if ! sshpass -p "$REMOTE_PASS" ssh -o StrictHostKeyChecking=no -o ConnectTimeout=5 \
    "${REMOTE_USER}@${REMOTE_HOST}" "echo 'Connected'" 2>/dev/null; then
    echo "ERROR: Cannot connect to ${REMOTE_HOST}"
    exit 1
fi

echo "✓ Connection successful"
echo ""

# Check if script exists on remote
if ! sshpass -p "$REMOTE_PASS" ssh -o StrictHostKeyChecking=no \
    "${REMOTE_USER}@${REMOTE_HOST}" \
    "test -f /opt/smom-dbis-138-proxmox/scripts/deployment/deploy-validated-set.sh" 2>/dev/null; then
    echo "ERROR: deploy-validated-set.sh not found on ${REMOTE_HOST}"
    exit 1
fi

echo "✓ Deployment script found"
echo ""

# Check if source project exists
if ! sshpass -p "$REMOTE_PASS" ssh -o StrictHostKeyChecking=no \
    "${REMOTE_USER}@${REMOTE_HOST}" \
    "test -d /opt/smom-dbis-138" 2>/dev/null; then
    echo "ERROR: Source project /opt/smom-dbis-138 not found on ${REMOTE_HOST}"
    exit 1
fi

echo "✓ Source project found"
echo ""

echo "Starting deployment..."
echo "This may take a while (up to 1 hour for full deployment)"
echo ""

# Run deployment with timeout (2 hours max)
sshpass -p "$REMOTE_PASS" ssh -o StrictHostKeyChecking=no \
    "${REMOTE_USER}@${REMOTE_HOST}" \
    "cd /opt/smom-dbis-138-proxmox && \
     chmod +x ./scripts/deployment/deploy-validated-set.sh && \
     timeout 7200 ./scripts/deployment/deploy-validated-set.sh \
       --source-project /opt/smom-dbis-138" 2>&1

EXIT_CODE=$?

if [[ $EXIT_CODE -eq 0 ]]; then
    echo ""
    echo "✅ Deployment completed successfully!"
elif [[ $EXIT_CODE -eq 124 ]]; then
    echo ""
    echo "⚠ Deployment timed out (2 hours)"
    echo "Check the deployment status manually"
else
    echo ""
    echo "❌ Deployment failed with exit code: $EXIT_CODE"
    echo "Check the output above for errors"
fi

exit $EXIT_CODE

