#!/bin/bash
# Script to copy deployment package to Proxmox host and run deployment
# This is the recommended approach for remote deployment

set -e

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

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m'

# Load environment
source "$SCRIPT_DIR/load-env.sh"
load_env_file

PROXMOX_HOST="${PROXMOX_HOST:-192.168.11.10}"
DEPLOY_DIR="/opt/smom-dbis-138-proxmox"
DEPLOY_SOURCE="$PROJECT_ROOT/smom-dbis-138-proxmox"

echo ""
echo -e "${CYAN}╔════════════════════════════════════════════════════════════════╗${NC}"
echo -e "${CYAN}║${NC}        Deploy to Proxmox Host: ${PROXMOX_HOST}              ${CYAN}║${NC}"
echo -e "${CYAN}╚════════════════════════════════════════════════════════════════╝${NC}"
echo ""

# Check if deployment directory exists locally
if [ ! -d "$DEPLOY_SOURCE" ]; then
    echo -e "${RED}❌ Deployment directory not found: $DEPLOY_SOURCE${NC}"
    echo -e "${YELLOW}Current directory: $(pwd)${NC}"
    echo -e "${YELLOW}Project root: $PROJECT_ROOT${NC}"
    exit 1
fi

echo -e "${BLUE}This script will:${NC}"
echo "  1. Copy deployment package to Proxmox host"
echo "  2. SSH into Proxmox host"
echo "  3. Run deployment on Proxmox host"
echo ""

read -p "$(echo -e ${YELLOW}Continue? [y/N]: ${NC})" -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo -e "${YELLOW}Deployment cancelled${NC}"
    exit 0
fi

echo ""
echo -e "${BLUE}Step 1: Copying deployment package to Proxmox host...${NC}"

# Create deployment package (exclude unnecessary files)
TEMP_DIR=$(mktemp -d)
DEPLOY_PACKAGE="$TEMP_DIR/smom-dbis-138-proxmox"

echo -e "${BLUE}Creating deployment package...${NC}"
if command -v rsync &> /dev/null; then
    rsync -av --exclude='.git' --exclude='node_modules' --exclude='*.log' \
        "$DEPLOY_SOURCE/" "$DEPLOY_PACKAGE/"
else
    # Fallback to tar if rsync not available
    cd "$PROJECT_ROOT"
    tar --exclude='.git' --exclude='node_modules' --exclude='*.log' \
        -czf "$TEMP_DIR/smom-dbis-138-proxmox.tar.gz" smom-dbis-138-proxmox/
    ssh root@"${PROXMOX_HOST}" "mkdir -p /opt && cd /opt && tar -xzf -" < "$TEMP_DIR/smom-dbis-138-proxmox.tar.gz"
    rm -f "$TEMP_DIR/smom-dbis-138-proxmox.tar.gz"
    echo -e "${GREEN}✅ Deployment package copied${NC}"
    DEPLOY_PACKAGE=""  # Skip scp step
fi

if [ -n "$DEPLOY_PACKAGE" ]; then
    echo -e "${BLUE}Copying to Proxmox host...${NC}"

    # Add host to known_hosts if not present (non-interactive)
    if ! ssh-keygen -F "${PROXMOX_HOST}" &>/dev/null; then
        echo -e "${YELLOW}Adding ${PROXMOX_HOST} to known_hosts...${NC}"
        ssh-keyscan -H "${PROXMOX_HOST}" >> ~/.ssh/known_hosts 2>/dev/null || true
    fi

    # Use StrictHostKeyChecking=accept-new for first connection (or if key changed)
    # Note: Will prompt for password if SSH key not configured
    echo -e "${YELLOW}Note: You may be prompted for the root password${NC}"
    
    # Ensure /opt exists on remote host
    ssh -o StrictHostKeyChecking=accept-new -o UserKnownHostsFile=~/.ssh/known_hosts \
        -o PreferredAuthentications=publickey,password \
        root@"${PROXMOX_HOST}" "mkdir -p /opt" || {
        echo -e "${RED}❌ Failed to create /opt directory. Check SSH authentication.${NC}"
        exit 1
    }
    
    # Remove old deployment if exists
    ssh -o StrictHostKeyChecking=accept-new -o UserKnownHostsFile=~/.ssh/known_hosts \
        -o PreferredAuthentications=publickey,password \
        root@"${PROXMOX_HOST}" "rm -rf $DEPLOY_DIR" 2>/dev/null || true
    
    # Copy files
    scp -o StrictHostKeyChecking=accept-new -o UserKnownHostsFile=~/.ssh/known_hosts \
        -o PreferredAuthentications=publickey,password \
        -r "$DEPLOY_PACKAGE" root@"${PROXMOX_HOST}:/opt/" || {
        echo -e "${RED}❌ Failed to copy files. Check SSH authentication.${NC}"
        echo -e "${YELLOW}You may need to:${NC}"
        echo "  1. Set up SSH key: ssh-copy-id root@${PROXMOX_HOST}"
        echo "  2. Or enter password when prompted"
        exit 1
    }
    
    # Verify files were copied
    echo -e "${BLUE}Verifying files were copied...${NC}"
    ssh -o StrictHostKeyChecking=accept-new -o UserKnownHostsFile=~/.ssh/known_hosts \
        -o PreferredAuthentications=publickey,password \
        root@"${PROXMOX_HOST}" "ls -la $DEPLOY_DIR/scripts/deployment/ 2>/dev/null | head -5 || echo 'Files not found at expected location'" || true
fi

# Cleanup temp directory
rm -rf "$TEMP_DIR"

echo -e "${GREEN}✅ Deployment package copied${NC}"

echo ""
echo -e "${BLUE}Step 2: Running deployment on Proxmox host...${NC}"
echo ""

# SSH and run deployment (with host key acceptance)
# Note: Will prompt for password if SSH key not configured
echo -e "${YELLOW}Note: You may be prompted for the root password again${NC}"

# Create a temporary script file to avoid heredoc issues
REMOTE_SCRIPT=$(cat << 'REMOTE_SCRIPT_END'
#!/bin/bash
set -e

DEPLOY_DIR="/opt/smom-dbis-138-proxmox"

echo "=========================================="
echo "Remote Deployment Script"
echo "=========================================="
echo "Target directory: $DEPLOY_DIR"
echo ""

# Check if directory exists
if [ ! -d "$DEPLOY_DIR" ]; then
    echo "ERROR: Directory $DEPLOY_DIR does not exist"
    echo ""
    echo "Checking /opt/ contents:"
    ls -la /opt/ || echo "Cannot access /opt/"
    echo ""
    echo "Looking for smom directories:"
    find /opt -type d -name "*smom*" 2>/dev/null || echo "No smom directories found"
    exit 1
fi

# Change to deployment directory
cd "$DEPLOY_DIR" || {
    echo "ERROR: Cannot change to $DEPLOY_DIR"
    exit 1
}

echo "Current directory: $(pwd)"
echo ""
echo "Directory structure:"
ls -la
echo ""

# Check for scripts directory
if [ ! -d "scripts" ]; then
    echo "ERROR: scripts directory not found"
    echo "Available directories:"
    find . -maxdepth 2 -type d | head -20
    exit 1
fi

# Check for deployment scripts
if [ ! -d "scripts/deployment" ]; then
    echo "ERROR: scripts/deployment directory not found"
    echo "Available in scripts/:"
    ls -la scripts/ || echo "Cannot list scripts/"
    exit 1
fi

# Make scripts executable
echo "Making scripts executable..."
find scripts/deployment -name "*.sh" -type f -exec chmod +x {} \; 2>/dev/null || true
find install -name "*.sh" -type f -exec chmod +x {} \; 2>/dev/null || true

# Verify deploy-all.sh exists
if [ ! -f "scripts/deployment/deploy-all.sh" ]; then
    echo "ERROR: scripts/deployment/deploy-all.sh not found"
    echo ""
    echo "Available deployment scripts:"
    find scripts/deployment -name "*.sh" -type f || echo "No .sh files found"
    exit 1
fi

echo "✅ Found deploy-all.sh"
echo ""
echo "Starting deployment..."
echo "=========================================="
echo ""

# Run deployment
exec ./scripts/deployment/deploy-all.sh
REMOTE_SCRIPT_END
)

# Execute the remote script via SSH
ssh -o StrictHostKeyChecking=accept-new -o UserKnownHostsFile=~/.ssh/known_hosts \
    -o PreferredAuthentications=publickey,password \
    root@"${PROXMOX_HOST}" bash <<< "$REMOTE_SCRIPT"

echo ""
echo -e "${GREEN}✅ Deployment completed!${NC}"
echo ""
echo "Next steps:"
echo "  1. Verify containers: ssh root@${PROXMOX_HOST} 'pct list'"
echo "  2. Check logs: ssh root@${PROXMOX_HOST} 'tail -f $DEPLOY_DIR/logs/*.log'"
echo "  3. Configure services as needed"
echo ""
echo -e "${BLUE}Tip:${NC} To avoid password prompts, set up SSH key:"
echo "  ssh-copy-id root@${PROXMOX_HOST}"

