#!/bin/bash

# ThrillWiki VM CI Setup Script
# This script helps set up the VM deployment system

set -e

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

log() {
    echo -e "${BLUE}[SETUP]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Configuration prompts
prompt_config() {
    log "Setting up ThrillWiki VM CI/CD system..."
    echo
    
    read -p "Enter your VM IP address: " VM_IP
    read -p "Enter your VM username (default: ubuntu): " VM_USER
    VM_USER=${VM_USER:-ubuntu}
    
    read -p "Enter your GitHub repository URL: " REPO_URL
    read -p "Enter your GitHub webhook secret: " WEBHOOK_SECRET
    
    read -p "Enter local webhook port (default: 9000): " WEBHOOK_PORT
    WEBHOOK_PORT=${WEBHOOK_PORT:-9000}
    
    read -p "Enter VM project path (default: /home/$VM_USER/thrillwiki): " VM_PROJECT_PATH
    VM_PROJECT_PATH=${VM_PROJECT_PATH:-/home/$VM_USER/thrillwiki}
}

# Create SSH key
setup_ssh() {
    log "Setting up SSH keys..."
    
    local ssh_key_path="$HOME/.ssh/thrillwiki_vm"
    
    if [ ! -f "$ssh_key_path" ]; then
        ssh-keygen -t rsa -b 4096 -f "$ssh_key_path" -N ""
        log_success "SSH key generated: $ssh_key_path"
        
        log "Please copy the following public key to your VM:"
        echo "---"
        cat "$ssh_key_path.pub"
        echo "---"
        echo
        log "Run this on your VM:"
        echo "mkdir -p ~/.ssh && echo '$(cat "$ssh_key_path.pub")' >> ~/.ssh/***REMOVED*** && chmod 600 ~/.ssh/***REMOVED***"
        echo
        read -p "Press Enter when you've added the key to your VM..."
    else
        log "SSH key already exists: $ssh_key_path"
    fi
    
    # Test SSH connection
    log "Testing SSH connection..."
    if ssh -i "$ssh_key_path" -o ConnectTimeout=5 -o StrictHostKeyChecking=no "$VM_USER@$VM_IP" "echo 'SSH connection successful'"; then
        log_success "SSH connection test passed"
    else
        log_error "SSH connection test failed"
        exit 1
    fi
}

# Create environment file
create_env_file() {
    log "Creating webhook environment file..."
    
    cat > ***REMOVED***.webhook << EOF
# ThrillWiki Webhook Configuration
WEBHOOK_PORT=$WEBHOOK_PORT
WEBHOOK_SECRET=$WEBHOOK_SECRET
VM_HOST=$VM_IP
VM_PORT=22
VM_USER=$VM_USER
VM_KEY_PATH=$HOME/.ssh/thrillwiki_vm
VM_PROJECT_PATH=$VM_PROJECT_PATH
REPO_URL=$REPO_URL
DEPLOY_BRANCH=main
EOF
    
    log_success "Environment file created: ***REMOVED***.webhook"
}

# Setup VM
setup_vm() {
    log "Setting up VM environment..."
    
    local ssh_key_path="$HOME/.ssh/thrillwiki_vm"
    
    # Create setup script for VM
    cat > /tmp/vm_setup.sh << 'EOF'
#!/bin/bash
set -e

echo "Setting up VM for ThrillWiki deployment..."

# Update system
sudo apt update

# Install required packages
sudo apt install -y git curl build-essential python3-pip lsof

# Install UV if not present
if ! command -v uv &> /dev/null; then
    echo "Installing UV..."
    curl -LsSf https://astral.sh/uv/install.sh | sh
    source ~/.cargo/env
fi

# Clone repository if not present
if [ ! -d "thrillwiki" ]; then
    echo "Cloning repository..."
    git clone REPO_URL_PLACEHOLDER thrillwiki
fi

cd thrillwiki

# Install dependencies
uv sync

# Create directories
mkdir -p logs backups

# Make scripts executable
chmod +x scripts/*.sh

echo "VM setup completed successfully!"
EOF
    
    # Replace placeholder with actual repo URL
    sed -i.bak "s|REPO_URL_PLACEHOLDER|$REPO_URL|g" /tmp/vm_setup.sh
    
    # Copy and execute setup script on VM
    scp -i "$ssh_key_path" /tmp/vm_setup.sh "$VM_USER@$VM_IP:/tmp/"
    ssh -i "$ssh_key_path" "$VM_USER@$VM_IP" "bash /tmp/vm_setup.sh"
    
    log_success "VM setup completed"
    
    # Cleanup
    rm /tmp/vm_setup.sh /tmp/vm_setup.sh.bak
}

# Install systemd services
setup_services() {
    log "Setting up systemd services on VM..."
    
    local ssh_key_path="$HOME/.ssh/thrillwiki_vm"
    
    # Copy service files and install them
    ssh -i "$ssh_key_path" "$VM_USER@$VM_IP" << EOF
cd thrillwiki

# Update service files with correct paths
sed -i 's|/home/ubuntu|/home/$VM_USER|g' scripts/systemd/*.service
sed -i 's|ubuntu|$VM_USER|g' scripts/systemd/*.service

# Install services
sudo cp scripts/systemd/thrillwiki.service /etc/systemd/system/
sudo cp scripts/systemd/thrillwiki-webhook.service /etc/systemd/system/

# Reload and enable services
sudo systemctl daemon-reload
sudo systemctl enable thrillwiki.service

echo "Services installed successfully!"
EOF
    
    log_success "Systemd services installed"
}

# Test deployment
test_deployment() {
    log "Testing VM deployment..."
    
    local ssh_key_path="$HOME/.ssh/thrillwiki_vm"
    
    ssh -i "$ssh_key_path" "$VM_USER@$VM_IP" << EOF
cd thrillwiki
./scripts/vm-deploy.sh
EOF
    
    log_success "Deployment test completed"
}

# Start webhook listener
start_webhook() {
    log "Starting webhook listener..."
    
    if [ -f "***REMOVED***.webhook" ]; then
        log "Webhook configuration found. You can start the webhook listener with:"
        echo "  source ***REMOVED***.webhook && python3 scripts/webhook-listener.py"
        echo
        log "Or run it in the background:"
        echo "  nohup python3 scripts/webhook-listener.py > logs/webhook.log 2>&1 &"
    else
        log_error "Webhook configuration not found!"
        exit 1
    fi
}

# GitHub webhook instructions
github_instructions() {
    log "GitHub Webhook Setup Instructions:"
    echo
    echo "1. Go to your GitHub repository: $REPO_URL"
    echo "2. Navigate to Settings → Webhooks"
    echo "3. Click 'Add webhook'"
    echo "4. Configure:"
    echo "   - Payload URL: http://YOUR_PUBLIC_IP:$WEBHOOK_PORT/webhook"
    echo "   - Content type: application/json"
    echo "   - Secret: $WEBHOOK_SECRET"
    echo "   - Events: Just the push event"
    echo "5. Click 'Add webhook'"
    echo
    log_warning "Make sure port $WEBHOOK_PORT is open on your firewall!"
}

# Main setup flow
main() {
    log "ThrillWiki VM CI/CD Setup"
    echo "=========================="
    echo
    
    # Create logs directory
    mkdir -p logs
    
    # Get configuration
    prompt_config
    
    # Setup steps
    setup_ssh
    create_env_file
    setup_vm
    setup_services
    test_deployment
    
    # Final instructions
    echo
    log_success "Setup completed successfully!"
    echo
    start_webhook
    echo
    github_instructions
    
    log "Setup log saved to: logs/setup.log"
}

# Run main function and log output
main "$@" 2>&1 | tee logs/setup.log