#!/usr/bin/env bash
#
# Fix Missing Deploy-Automation Script 
# Deploys the missing deploy-automation.sh script to fix systemd service startup failure
#

set -e

# Script configuration
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(cd "$SCRIPT_DIR/../.." && pwd)"

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

# Configuration
REMOTE_HOST="${1:-192.168.20.65}"
REMOTE_USER="${2:-thrillwiki}"
REMOTE_PORT="${3:-22}"
SSH_KEY="${4:-$HOME/.ssh/thrillwiki_vm}"
REMOTE_PATH="/home/$REMOTE_USER/thrillwiki"

# Enhanced SSH options to handle authentication issues
SSH_OPTS="-i $SSH_KEY -o IdentitiesOnly=yes -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o ConnectTimeout=30 -o PasswordAuthentication=no -o PreferredAuthentications=publickey -o ServerAliveInterval=60"

echo -e "${BOLD}${CYAN}🚀 Fix Missing Deploy-Automation Script${NC}"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
echo "Target: ${REMOTE_USER}@${REMOTE_HOST}:${REMOTE_PORT}"
echo "SSH Key: $SSH_KEY"
echo "Remote Path: $REMOTE_PATH"
echo "Local Script: $SCRIPT_DIR/deploy-automation.sh"
echo ""

# Function to run remote commands with proper SSH authentication
run_remote() {
    local cmd="$1"
    local description="$2"
    local use_sudo="${3:-false}"
    
    echo -e "${YELLOW}🔧 ${description}${NC}"
    
    if [ "$use_sudo" = "true" ]; then
        ssh $SSH_OPTS -p $REMOTE_PORT -t $REMOTE_USER@$REMOTE_HOST "sudo $cmd" 2>/dev/null || {
            echo -e "${RED}❌ Failed: $description${NC}"
            return 1
        }
    else
        ssh $SSH_OPTS -p $REMOTE_PORT $REMOTE_USER@$REMOTE_HOST "$cmd" 2>/dev/null || {
            echo -e "${RED}❌ Failed: $description${NC}"
            return 1
        }
    fi
    
    echo -e "${GREEN}✅ Success: $description${NC}"
    return 0
}

# Function to copy files to remote server
copy_to_remote() {
    local local_file="$1"
    local remote_file="$2"
    local description="$3"
    
    echo -e "${YELLOW}📁 ${description}${NC}"
    
    if scp $SSH_OPTS -P $REMOTE_PORT "$local_file" "$REMOTE_USER@$REMOTE_HOST:$remote_file" 2>/dev/null; then
        echo -e "${GREEN}✅ Success: $description${NC}"
        return 0
    else
        echo -e "${RED}❌ Failed: $description${NC}"
        return 1
    fi
}

# Check if SSH key exists
echo -e "${BLUE}🔑 Checking SSH authentication...${NC}"
if [ ! -f "$SSH_KEY" ]; then
    echo -e "${RED}❌ SSH key not found: $SSH_KEY${NC}"
    echo "Please ensure the SSH key exists and has correct permissions"
    exit 1
fi

# Check SSH key permissions
ssh_key_perms=$(stat -c %a "$SSH_KEY" 2>/dev/null || stat -f %A "$SSH_KEY" 2>/dev/null)
if [ "$ssh_key_perms" != "600" ]; then
    echo -e "${YELLOW}⚠️  Fixing SSH key permissions...${NC}"
    chmod 600 "$SSH_KEY"
fi

# Test SSH connection
echo -e "${BLUE}🔗 Testing SSH connection...${NC}"
if ssh $SSH_OPTS -p $REMOTE_PORT $REMOTE_USER@$REMOTE_HOST "echo 'SSH connection successful'" 2>/dev/null; then
    echo -e "${GREEN}✅ SSH connection verified${NC}"
else
    echo -e "${RED}❌ SSH connection failed${NC}"
    echo "Please check:"
    echo "1. SSH key is correct: $SSH_KEY"
    echo "2. Remote host is accessible: $REMOTE_HOST"
    echo "3. Remote user exists: $REMOTE_USER"
    echo "4. SSH key is authorized on remote server"
    exit 1
fi

# Check if local deploy-automation.sh exists
echo -e "${BLUE}📋 Checking local script...${NC}"
LOCAL_SCRIPT="$SCRIPT_DIR/deploy-automation.sh"
if [ ! -f "$LOCAL_SCRIPT" ]; then
    echo -e "${RED}❌ Local script not found: $LOCAL_SCRIPT${NC}"
    exit 1
fi
echo -e "${GREEN}✅ Local script found: $LOCAL_SCRIPT${NC}"

# Create remote directory structure if needed
run_remote "mkdir -p $REMOTE_PATH/scripts/vm" "Creating remote scripts directory"

# Deploy the deploy-automation.sh script
copy_to_remote "$LOCAL_SCRIPT" "$REMOTE_PATH/scripts/vm/deploy-automation.sh" "Deploying deploy-automation.sh script"

# Set executable permissions
run_remote "chmod +x $REMOTE_PATH/scripts/vm/deploy-automation.sh" "Setting executable permissions"

# Verify script deployment
echo -e "${BLUE}🔍 Verifying script deployment...${NC}"
run_remote "ls -la $REMOTE_PATH/scripts/vm/deploy-automation.sh" "Verifying script exists and has correct permissions"

# Test script execution
echo -e "${BLUE}🧪 Testing script functionality...${NC}"
run_remote "cd $REMOTE_PATH && ./scripts/vm/deploy-automation.sh status" "Testing script execution"

# Restart systemd service
echo -e "${BLUE}🔄 Restarting systemd service...${NC}"
run_remote "systemctl --user restart thrillwiki-deployment.service" "Restarting thrillwiki-deployment service"

# Wait for service to start
echo -e "${YELLOW}⏳ Waiting for service to start...${NC}"
sleep 10

# Check service status
echo -e "${BLUE}📊 Checking service status...${NC}"
if run_remote "systemctl --user is-active thrillwiki-deployment.service" "Checking if service is active"; then
    echo ""
    echo -e "${GREEN}${BOLD}🎉 SUCCESS: Systemd service startup fix completed!${NC}"
    echo ""
    echo "✅ deploy-automation.sh script deployed successfully"
    echo "✅ Script has executable permissions"
    echo "✅ Script functionality verified"
    echo "✅ Systemd service restarted"
    echo "✅ Service is now active and running"
    echo ""
    echo -e "${CYAN}Service Status:${NC}"
    run_remote "systemctl --user status thrillwiki-deployment.service --no-pager -l" "Getting detailed service status"
else
    echo ""
    echo -e "${YELLOW}⚠️  Service restarted but may still be starting up${NC}"
    echo "Checking detailed status..."
    run_remote "systemctl --user status thrillwiki-deployment.service --no-pager -l" "Getting detailed service status"
fi

echo ""
echo -e "${BOLD}${CYAN}🔧 Fix Summary${NC}"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "• Missing script deployed: ✅ [AWS-SECRET-REMOVED]eploy-automation.sh"
echo "• Executable permissions: ✅ chmod +x applied"
echo "• Script functionality: ✅ Tested and working"
echo "• Systemd service: ✅ Restarted"
echo "• Error 203/EXEC: ✅ Should be resolved"
echo ""
echo "The systemd service startup failure has been fixed!"