#!/bin/bash
#
# ThrillWiki Template VM Management Utilities
# Quick helpers for managing template VMs on Unraid
#

# Set strict mode
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}[TEMPLATE]${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
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(cd "$SCRIPT_DIR/../.." && pwd)"

# Load environment variables if available
if [[ -f "$PROJECT_DIR/***REMOVED***.unraid" ]]; then
    source "$PROJECT_DIR/***REMOVED***.unraid"
else
    log_error "No ***REMOVED***.unraid file found. Please run setup-complete-automation.sh first."
    exit 1
fi

# Function to show help
show_help() {
    echo "ThrillWiki Template VM Management Utilities"
    echo ""
    echo "Usage:"
    echo "  $0 check           Check if template exists and is ready"
    echo "  $0 info            Show template information"
    echo "  $0 list            List all template-based VM instances"
    echo "  $0 copy VM_NAME    Copy template to new VM"
    echo "  $0 deploy VM_NAME  Deploy complete VM from template"
    echo "  $0 status          Show template VM status"
    echo "  $0 update          Update template VM (instructions)"
    echo "  $0 autopull        Manage auto-pull functionality"
    echo ""
    echo "Auto-pull Commands:"
    echo "  $0 autopull status      Show auto-pull status on VMs"
    echo "  $0 autopull enable VM   Enable auto-pull on specific VM"
    echo "  $0 autopull disable VM  Disable auto-pull on specific VM"
    echo "  $0 autopull logs VM     Show auto-pull logs from VM"
    echo "  $0 autopull test VM     Test auto-pull on specific VM"
    echo ""
    echo "Examples:"
    echo "  $0 check                    # Verify template is ready"
    echo "  $0 copy thrillwiki-prod     # Copy template to new VM"
    echo "  $0 deploy thrillwiki-test   # Complete deployment from template"
    echo "  $0 autopull status          # Check auto-pull status on all VMs"
    echo "  $0 autopull logs $VM_NAME   # View auto-pull logs"
    exit 0
}

# Check if required environment variables are set
check_environment() {
    if [[ -z "$UNRAID_HOST" ]]; then
        log_error "UNRAID_HOST not set. Please configure your environment."
        exit 1
    fi
    
    if [[ -z "$UNRAID_USER" ]]; then
        UNRAID_USER="root"
        log "Using default UNRAID_USER: $UNRAID_USER"
    fi
    
    log_success "Environment configured: $UNRAID_USER@$UNRAID_HOST"
}

# Function to run python template manager commands
run_template_manager() {
    cd "$SCRIPT_DIR"
    export UNRAID_HOST="$UNRAID_HOST"
    export UNRAID_USER="$UNRAID_USER"
    python3 template_manager.py "$@"
}

# Function to run template-based main script
run_main_template() {
    cd "$SCRIPT_DIR"
    
    # Export all environment variables
    export UNRAID_HOST="$UNRAID_HOST"
    export UNRAID_USER="$UNRAID_USER"
    export VM_NAME="$1"
    export VM_MEMORY="${VM_MEMORY:-4096}"
    export VM_VCPUS="${VM_VCPUS:-2}"
    export VM_DISK_SIZE="${VM_DISK_SIZE:-50}"
    export VM_IP="${VM_IP:-dhcp}"
    export REPO_URL="${REPO_URL:-}"
    export GITHUB_TOKEN="${GITHUB_TOKEN:-}"
    
    shift  # Remove VM_NAME from arguments
    python3 main_template.py "$@"
}

# Parse command line arguments
case "${1:-}" in
    check)
        log "🔍 Checking template VM availability..."
        check_environment
        run_template_manager check
        ;;
    
    info)
        log "📋 Getting template VM information..."
        check_environment
        run_template_manager info
        ;;
    
    list)
        log "📋 Listing template-based VM instances..."
        check_environment
        run_template_manager list
        ;;
    
    copy)
        if [[ -z "${2:-}" ]]; then
            log_error "VM name is required for copy operation"
            echo "Usage: $0 copy VM_NAME"
            exit 1
        fi
        
        log "💾 Copying template to VM: $2"
        check_environment
        run_template_manager copy "$2"
        ;;
    
    deploy)
        if [[ -z "${2:-}" ]]; then
            log_error "VM name is required for deploy operation"
            echo "Usage: $0 deploy VM_NAME"
            exit 1
        fi
        
        log "🚀 Deploying complete VM from template: $2"
        check_environment
        run_main_template "$2" deploy
        ;;
    
    status)
        log "📊 Checking template VM status..."
        check_environment
        
        # Check template VM status directly
        ssh "$UNRAID_USER@$UNRAID_HOST" "virsh domstate thrillwiki-template-ubuntu" 2>/dev/null || {
            log_error "Could not check template VM status"
            exit 1
        }
        ;;
    
    update)
        log "🔄 Template VM update instructions:"
        echo ""
        echo "To update your template VM:"
        echo "1. Start the template VM on Unraid"
        echo "2. SSH into the template VM"
        echo "3. Update packages: sudo apt update && sudo apt upgrade -y"
        echo "4. Update ThrillWiki dependencies if needed"
        echo "5. Clean up temporary files: sudo apt autoremove && sudo apt autoclean"
        echo "6. Clear bash history: history -c && history -w"
        echo "7. Shutdown the template VM: sudo shutdown now"
        echo "8. The updated disk is now ready as a template"
        echo ""
        log_warning "IMPORTANT: Template VM must be stopped before creating new instances"
        
        check_environment
        run_template_manager update
        ;;
    
    autopull)
        shift # Remove 'autopull' from arguments
        autopull_command="${1:-status}"
        vm_name="${2:-$VM_NAME}"
        
        log "🔄 Managing auto-pull functionality..."
        check_environment
        
        # Get list of all template VMs
        if [[ "$autopull_command" == "status" ]] && [[ "$vm_name" == "$VM_NAME" ]]; then
            all_vms=$(run_template_manager list | grep -E "(running|shut off)" | awk '{print $2}' || echo "")
        else
            all_vms=$vm_name
        fi
        
        if [[ -z "$all_vms" ]]; then
            log_warning "No running template VMs found to manage auto-pull on."
            exit 0
        fi
        
        for vm in $all_vms; do
            log "====== Auto-pull for VM: $vm ======"
            
            case "$autopull_command" in
                status)
                    ssh "$vm" "[AWS-SECRET-REMOVED]uto-pull.sh --status"
                    ;;
                enable)
                    ssh "$vm" "(crontab -l 2>/dev/null || echo \"\") | { cat; echo \"*/10 * * * * [AWS-SECRET-REMOVED]uto-pull.sh >> /home/thrillwiki/logs/cron.log 2>&1\"; } | crontab - && echo '✅ Auto-pull enabled' || echo '❌ Failed to enable'"
                    ;;
                disable)
                    ssh "$vm" "crontab -l 2>/dev/null | grep -v 'auto-pull.sh' | crontab - && echo '✅ Auto-pull disabled' || echo '❌ Failed to disable'"
                    ;;
                logs)
                    ssh "$vm" "[AWS-SECRET-REMOVED]uto-pull.sh --logs"
                    ;;
                test)
                    ssh "$vm" "[AWS-SECRET-REMOVED]uto-pull.sh --force"
                    ;;
                *)
                    log_error "Invalid auto-pull command: $autopull_command"
                    show_help
                    exit 1
                    ;;
            esac
            echo
        done
        ;;
    
    --help|-h|help|"")
        show_help
        ;;
    
    *)
        log_error "Unknown command: ${1:-}"
        echo ""
        show_help
        ;;
esac
