#!/bin/bash
# MyISA Control Tool - Unified command line interface
# Manages staging/production environment switching and package synchronization
# Consolidates all functionality in a single script

set -e

# Configuration
STAGING_FILE="/root/.staging"
PROD_PACKAGE="myisa-b2b-kiosk"
STAGING_PACKAGE="myisa-b2b-staging-kiosk"
SERVICE_NAME="myisa-kiosk.service"
REPO_URL="https://mirror.mintt.cloud/secure-repo"

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

# Help function
show_help() {
    echo "🔧 MyISA Control Tool (myisactl)"
    echo ""
    echo "Usage: myisactl [COMMAND]"
    echo ""
    echo "Available commands:"
    echo "  enable-staging    Enable staging mode"
    echo "  enable-production Enable production mode"
    echo "  status           Show current environment status"
    echo "  sync             Sync packages according to current mode"
    echo "  upgrade          Update MyISA packages (not system packages)"
    echo "  check            Check for MyISA package updates"
    echo "  setup-repo       Setup MyISA B2B APT repository"
    echo "  rustdesk-start   Start RustDesk remote access (shows ID)"
    echo "  rustdesk-stop    Stop RustDesk remote access"
    echo "  rustdesk-status  Show RustDesk connection status"
    echo "  help             Show this help"
    echo ""
    echo "Examples:"
    echo "  myisactl enable-staging    # Switch to staging mode"
    echo "  myisactl enable-production # Switch to production mode"
    echo "  myisactl status           # Check current mode"
    echo "  myisactl sync             # Sync packages"
    echo "  myisactl upgrade          # Update MyISA packages only"
    echo "  myisactl check            # Check if MyISA package upgrade is needed"
    echo "  myisactl setup-repo       # Setup MyISA B2B APT repository"
    echo "  myisactl rustdesk-start   # Start RustDesk and display connection ID"
    echo "  myisactl rustdesk-stop    # Stop RustDesk service"
    echo ""
    echo "Environment Management:"
    echo "  The tool uses /root/.staging file to determine environment:"
    echo "  - File present  → STAGING mode (staging package version)"
    echo "  - File absent   → PRODUCTION mode (production package version)"
    echo ""
    echo "Remote Access:"
    echo "  RustDesk is available for remote support but NOT auto-started"
    echo "  Start it manually when needed to avoid system freezes"
}

# Function to check if staging mode is enabled
is_staging_enabled() {
    [ -f "$STAGING_FILE" ]
}

# Function to check if a package is installed
is_package_installed() {
    local package="$1"
    dpkg -l "$package" 2>/dev/null | grep -q "^ii"
}

# Function to install a package
install_package() {
    local package="$1"
    echo "📦 Installing package $package..."
    
    # Update package list
    apt update
    
    # Install package
    apt install -y "$package"
    
    echo "✅ Package $package installed successfully"
}

# Function to uninstall a package
uninstall_package() {
    local package="$1"
    echo "🗑️  Uninstalling package $package..."
    
    # Stop service before uninstalling
    systemctl stop "$SERVICE_NAME" 2>/dev/null || true
    
    # Uninstall package
    apt remove -y "$package"
    
    echo "✅ Package $package uninstalled successfully"
}

# Function to restart service
restart_service() {
    echo "🔄 Restarting service $SERVICE_NAME..."
    systemctl daemon-reload
    systemctl enable "$SERVICE_NAME"
    systemctl start "$SERVICE_NAME"
    echo "✅ Service restarted"
}

# Function to enable staging mode
enable_staging() {
    echo "🧪 Enabling STAGING mode..."
    
    # Create switch file
    touch "$STAGING_FILE"
    chmod 644 "$STAGING_FILE"
    
    echo -e "✅ ${YELLOW}STAGING${NC} mode enabled"
    echo "   File created: $STAGING_FILE"
    
    # Sync packages
    echo "🔄 Syncing packages..."
    sync_packages_internal
}

# Function to enable production mode
enable_production() {
    echo "🚀 Enabling PRODUCTION mode..."
    
    # Remove switch file
    if [ -f "$STAGING_FILE" ]; then
        rm "$STAGING_FILE"
        echo -e "✅ ${GREEN}PRODUCTION${NC} mode enabled"
        echo "   File removed: $STAGING_FILE"
    else
        echo -e "✅ ${GREEN}PRODUCTION${NC} mode already active"
    fi
    
    # Sync packages
    echo "🔄 Syncing packages..."
    sync_packages_internal
}

# Internal synchronization function (used by enable commands)
sync_packages_internal() {
    echo "🔍 Checking package synchronization..."
    echo ""
    
    local staging_mode=$(is_staging_enabled && echo "true" || echo "false")
    local prod_installed=$(is_package_installed "$PROD_PACKAGE" && echo "true" || echo "false")
    local staging_installed=$(is_package_installed "$STAGING_PACKAGE" && echo "true" || echo "false")
    
    echo "Staging mode: $staging_mode"
    echo "Production package installed: $prod_installed"
    echo "Staging package installed: $staging_installed"
    echo ""
    
    # Synchronization logic
    if [ "$staging_mode" = "true" ]; then
        echo "🧪 STAGING mode detected"
        
        if [ "$staging_installed" = "true" ]; then
            echo "✅ Staging package already installed, nothing to do"
        elif [ "$prod_installed" = "true" ]; then
            echo "🔄 Uninstalling production package and installing staging package..."
            uninstall_package "$PROD_PACKAGE"
            install_package "$STAGING_PACKAGE"
            restart_service
        else
            echo "📦 Installing staging package..."
            install_package "$STAGING_PACKAGE"
            restart_service
        fi
    else
        echo "🚀 PRODUCTION mode detected"
        
        # Check if production package is available
        if apt-cache policy "$PROD_PACKAGE" 2>/dev/null | grep -q "Candidate:" && ! apt-cache policy "$PROD_PACKAGE" 2>/dev/null | grep -q "Candidate: (none)"; then
            echo "✅ Production package is available"
            
            if [ "$prod_installed" = "true" ]; then
                echo "✅ Production package already installed, nothing to do"
            elif [ "$staging_installed" = "true" ]; then
                echo "🔄 Uninstalling staging package and installing production package..."
                uninstall_package "$STAGING_PACKAGE"
                install_package "$PROD_PACKAGE"
                restart_service
            else
                echo "📦 Installing production package..."
                install_package "$PROD_PACKAGE"
                restart_service
            fi
        else
            echo "⚠️  Production package not available, keeping staging package"
            if [ "$staging_installed" = "false" ]; then
                echo "📦 Installing staging package as fallback..."
                install_package "$STAGING_PACKAGE"
                restart_service
            fi
        fi
    fi
    
    echo ""
    echo "✅ Synchronization completed"
}

# Function to sync packages (public interface)
sync_packages() {
    echo "🔄 Syncing packages..."
    sync_packages_internal
}

# Function to display comprehensive status
show_status() {
    echo "📊 MyISA Environment Status:"
    echo ""
    
    # Environment mode
    if is_staging_enabled; then
        echo -e "Environment: ${YELLOW}STAGING${NC} 🧪"
        echo "File: $STAGING_FILE (present)"
    else
        echo -e "Environment: ${GREEN}PRODUCTION${NC} 🚀"
        echo "File: $STAGING_FILE (absent)"
    fi
    
    echo ""
    echo "Packages:"
    if is_package_installed "$PROD_PACKAGE"; then
        echo -e "  $PROD_PACKAGE: ${GREEN}INSTALLED${NC}"
    else
        echo -e "  $PROD_PACKAGE: ${RED}NOT INSTALLED${NC}"
    fi
    
    if is_package_installed "$STAGING_PACKAGE"; then
        echo -e "  $STAGING_PACKAGE: ${GREEN}INSTALLED${NC}"
    else
        echo -e "  $STAGING_PACKAGE: ${RED}NOT INSTALLED${NC}"
    fi
    
    echo ""
    echo "Service:"
    if systemctl is-active --quiet "$SERVICE_NAME"; then
        echo -e "  $SERVICE_NAME: ${GREEN}ACTIVE${NC}"
    else
        echo -e "  $SERVICE_NAME: ${RED}INACTIVE${NC}"
    fi
    
    echo ""
    echo "Versions:"
    
    # Local installed version
    if is_staging_enabled; then
        if is_package_installed "$STAGING_PACKAGE"; then
            local_version=$(dpkg -l "$STAGING_PACKAGE" 2>/dev/null | grep "^ii" | awk '{print $3}' || echo "Unknown")
            echo -e "  Local (staging): ${GREEN}$local_version${NC}"
        else
            echo -e "  Local (staging): ${RED}NOT INSTALLED${NC}"
        fi
    else
        if is_package_installed "$PROD_PACKAGE"; then
            local_version=$(dpkg -l "$PROD_PACKAGE" 2>/dev/null | grep "^ii" | awk '{print $3}' || echo "Unknown")
            echo -e "  Local (production): ${GREEN}$local_version${NC}"
        else
            echo -e "  Local (production): ${RED}NOT INSTALLED${NC}"
        fi
    fi
    
    # Version distante disponible
    echo "  Checking remote versions..."
    apt update >/dev/null 2>&1 || true
    
    if is_staging_enabled; then
        remote_version=$(apt-cache policy "$STAGING_PACKAGE" 2>/dev/null | grep "Candidate:" | awk '{print $2}' || echo "Unknown")
        if [ "$remote_version" != "Unknown" ] && [ "$remote_version" != "(none)" ]; then
            echo -e "  Remote (staging): ${YELLOW}$remote_version${NC}"
        else
            echo -e "  Remote (staging): ${RED}NOT AVAILABLE${NC}"
        fi
    else
        remote_version=$(apt-cache policy "$PROD_PACKAGE" 2>/dev/null | grep "Candidate:" | awk '{print $2}' || echo "Unknown")
        if [ "$remote_version" != "Unknown" ] && [ "$remote_version" != "(none)" ]; then
            echo -e "  Remote (production): ${YELLOW}$remote_version${NC}"
        else
            echo -e "  Remote (production): ${RED}NOT AVAILABLE${NC}"
        fi
    fi
    
    # Comparaison des versions
    if [ "$local_version" != "Unknown" ] && [ "$remote_version" != "Unknown" ] && [ "$remote_version" != "NOT AVAILABLE" ]; then
        if [ "$local_version" = "$remote_version" ]; then
            echo -e "  Status: ${GREEN}UP TO DATE${NC} ✅"
        else
            echo -e "  Status: ${YELLOW}UPDATE AVAILABLE${NC} ⚠️"
            echo "  Run 'myisactl upgrade' to update"
        fi
    fi
}

# Function to upgrade MyISA packages only
upgrade_system() {
    echo "🔄 Upgrading MyISA packages..."
    echo ""

    # Update package list
    echo "📦 Updating package list..."
    apt update

    # Determine which package to check based on mode
    local staging_mode=$(is_staging_enabled && echo "true" || echo "false")
    local target_package=""

    if [ "$staging_mode" = "true" ]; then
        target_package="$STAGING_PACKAGE"
        echo "🧪 Checking staging package: $target_package"
    else
        target_package="$PROD_PACKAGE"
        echo "🚀 Checking production package: $target_package"
    fi

    # Check if package is installed
    if ! is_package_installed "$target_package"; then
        echo "⚠️  Package $target_package is not installed"
        echo "🔄 Installing package..."
        install_package "$target_package"
        restart_service
        echo "✅ Upgrade process completed"
        return
    fi

    # Get current and available versions
    local_version=$(dpkg -l "$target_package" 2>/dev/null | grep "^ii" | awk '{print $3}')
    remote_version=$(apt-cache policy "$target_package" 2>/dev/null | grep "Candidate:" | awk '{print $2}')

    echo "Current version: $local_version"
    echo "Available version: $remote_version"
    echo ""

    # Check if upgrade is needed
    if [ "$local_version" = "$remote_version" ]; then
        echo "✅ Package is already up to date"
    else
        echo "⬆️  Upgrading package $target_package..."
        apt install --only-upgrade -y "$target_package"
        echo "✅ Package upgraded successfully"
        restart_service
    fi

    echo ""
    echo "✅ Upgrade process completed"
}

# Function to check if upgrade is needed
check_upgrade() {
    echo "🔍 Checking MyISA package status..."
    echo ""

    # Update package list
    echo "📦 Updating package list..."
    apt update >/dev/null 2>&1 || true

    # Check MyISA package status
    local staging_mode=$(is_staging_enabled && echo "true" || echo "false")
    local target_package=""

    if [ "$staging_mode" = "true" ]; then
        target_package="$STAGING_PACKAGE"
        echo "🧪 Checking staging package: $target_package"
    else
        target_package="$PROD_PACKAGE"
        echo "🚀 Checking production package: $target_package"
    fi

    # Check if package is installed
    if ! is_package_installed "$target_package"; then
        echo "⚠️  Package $target_package is not installed"
        echo ""
        echo "🔄 INSTALLATION NEEDED"
        echo "Run: myisactl upgrade"
        exit 1
    fi

    # Get current and available versions
    local_version=$(dpkg -l "$target_package" 2>/dev/null | grep "^ii" | awk '{print $3}')
    remote_version=$(apt-cache policy "$target_package" 2>/dev/null | grep "Candidate:" | awk '{print $2}')

    echo "Current version: $local_version"
    echo "Available version: $remote_version"
    echo ""

    # Check if upgrade is needed
    if [ "$local_version" = "$remote_version" ]; then
        echo "✅ NO UPGRADE NEEDED"
        echo "Package is up to date"
        exit 0
    else
        echo "🔄 UPGRADE AVAILABLE"
        echo "Run: myisactl upgrade"
        exit 1
    fi
}

# Function to setup MyISA B2B APT repository
setup_repo() {
    echo "🔧 Setting up MyISA B2B APT repository..."
    echo "Repository URL: $REPO_URL"
    echo ""

    # Add GPG key (modern method) - force overwrite if exists
    echo "🔑 Adding repository GPG key..."
    rm -f /etc/apt/trusted.gpg.d/myisa-b2b.gpg
    if wget -qO - "$REPO_URL/repo-key.gpg" | gpg --dearmor -o /etc/apt/trusted.gpg.d/myisa-b2b.gpg 2>/dev/null; then
        chmod 644 /etc/apt/trusted.gpg.d/myisa-b2b.gpg
        echo "✅ GPG key added successfully"
    else
        echo "❌ Failed to download GPG key"
        echo "   Check network connectivity and repository access"
        exit 1
    fi

    # Add repository to sources.list.d - force overwrite
    echo "📦 Adding repository to APT sources..."
    mkdir -p /etc/apt/sources.list.d
    echo "deb [arch=amd64] $REPO_URL stable main" > /etc/apt/sources.list.d/myisa-b2b.list
    chmod 644 /etc/apt/sources.list.d/myisa-b2b.list
    echo "deb [arch=amd64] $REPO_URL stable main"

    # Update package list
    echo "🔄 Updating package list..."
    if apt update; then
        echo "✅ Package list updated"
    else
        echo "⚠️  Warning: apt update encountered issues"
        echo "   Repository may still be functional"
    fi

    echo ""
    echo "✅ MyISA B2B repository configured successfully!"
    echo ""
    echo "Available packages:"
    echo "  - myisa-b2b-kiosk: Kiosk version with automatic service"
    echo "  - myisa-b2b-staging-kiosk: Staging kiosk version"
    echo ""
    echo "Install commands:"
    echo "  apt install myisa-b2b-kiosk           # For production kiosk deployment"
    echo "  apt install myisa-b2b-staging-kiosk  # For staging kiosk deployment"
    echo ""
    echo "Repository key: $REPO_URL/repo-key.gpg"
}

# Function to start RustDesk
rustdesk_start() {
    echo "🚀 Starting RustDesk remote access..."
    echo ""

    # Check if RustDesk is installed
    if ! command -v rustdesk >/dev/null 2>&1; then
        echo -e "${RED}❌ RustDesk is not installed${NC}"
        echo "RustDesk should have been installed during system setup"
        exit 1
    fi

    # Check if already running
    if systemctl is-active --quiet rustdesk.service; then
        echo -e "${YELLOW}⚠️  RustDesk is already running${NC}"
        echo ""
        rustdesk_status
        exit 0
    fi

    # Start RustDesk service
    echo "📡 Starting RustDesk service..."
    systemctl start rustdesk.service

    # Wait for service to start
    sleep 2

    # Start hide window service
    echo "🪟 Starting window hide service..."
    systemctl start hide-rustdesk.service 2>/dev/null || true

    # Wait a bit for RustDesk to initialize
    echo "⏳ Waiting for RustDesk to initialize..."
    sleep 3

    # Get RustDesk ID
    echo ""
    echo "═══════════════════════════════════════════"
    echo "📋 RustDesk Connection Information"
    echo "═══════════════════════════════════════════"

    # Try to read ID from config
    if [ -f /root/.config/rustdesk/RustDesk2.toml ]; then
        RUSTDESK_ID=$(grep "^id = " /root/.config/rustdesk/RustDesk2.toml 2>/dev/null | cut -d'"' -f2)
        if [ -n "$RUSTDESK_ID" ]; then
            echo -e "RustDesk ID: ${GREEN}${RUSTDESK_ID}${NC}"
        fi
    fi

    # If not found in config, try to get it from rustdesk command
    if [ -z "$RUSTDESK_ID" ]; then
        RUSTDESK_ID=$(rustdesk --get-id 2>/dev/null | tr -d '\n' || echo "")
        if [ -n "$RUSTDESK_ID" ]; then
            echo -e "RustDesk ID: ${GREEN}${RUSTDESK_ID}${NC}"
        else
            echo -e "${YELLOW}⚠️  RustDesk ID not yet available${NC}"
            echo "Wait a few seconds and check: journalctl -u rustdesk.service"
        fi
    fi

    # Show server info
    echo "Server: openapi.mintt.cloud"
    echo "Protocol: WebSocket (port 443)"
    echo "═══════════════════════════════════════════"
    echo ""
    echo -e "${GREEN}✅ RustDesk started successfully${NC}"
    echo ""
    echo "To stop: myisactl rustdesk-stop"
    echo "To check status: myisactl rustdesk-status"
}

# Function to stop RustDesk
rustdesk_stop() {
    echo "🛑 Stopping RustDesk remote access..."
    echo ""

    # Check if running
    if ! systemctl is-active --quiet rustdesk.service; then
        echo -e "${YELLOW}⚠️  RustDesk is not running${NC}"
        exit 0
    fi

    # Stop hide window service first
    echo "🪟 Stopping window hide service..."
    systemctl stop hide-rustdesk.service 2>/dev/null || true

    # Stop RustDesk service
    echo "📡 Stopping RustDesk service..."
    systemctl stop rustdesk.service

    # Wait for clean shutdown
    sleep 1

    echo ""
    echo -e "${GREEN}✅ RustDesk stopped successfully${NC}"
    echo ""
    echo "To restart: myisactl rustdesk-start"
}

# Function to show RustDesk status
rustdesk_status() {
    echo "📊 RustDesk Status:"
    echo ""

    # Check if RustDesk is installed
    if ! command -v rustdesk >/dev/null 2>&1; then
        echo -e "Installation: ${RED}NOT INSTALLED${NC}"
        exit 1
    fi

    echo -e "Installation: ${GREEN}INSTALLED${NC}"

    # Check version
    RUSTDESK_VERSION=$(rustdesk --version 2>/dev/null | head -1 || echo "Unknown")
    echo "Version: $RUSTDESK_VERSION"

    echo ""
    echo "Services:"

    # Check rustdesk service
    if systemctl is-active --quiet rustdesk.service; then
        echo -e "  rustdesk.service: ${GREEN}ACTIVE${NC}"
    else
        echo -e "  rustdesk.service: ${RED}INACTIVE${NC}"
    fi

    # Check hide-rustdesk service
    if systemctl is-active --quiet hide-rustdesk.service; then
        echo -e "  hide-rustdesk.service: ${GREEN}ACTIVE${NC}"
    else
        echo -e "  hide-rustdesk.service: ${RED}INACTIVE${NC}"
    fi

    echo ""

    # Show connection info if running
    if systemctl is-active --quiet rustdesk.service; then
        echo "Connection Information:"

        # Try to get ID from config
        if [ -f /root/.config/rustdesk/RustDesk2.toml ]; then
            RUSTDESK_ID=$(grep "^id = " /root/.config/rustdesk/RustDesk2.toml 2>/dev/null | cut -d'"' -f2)
            if [ -n "$RUSTDESK_ID" ]; then
                echo -e "  ID: ${GREEN}${RUSTDESK_ID}${NC}"
            fi
        fi

        # If not found, try command
        if [ -z "$RUSTDESK_ID" ]; then
            RUSTDESK_ID=$(rustdesk --get-id 2>/dev/null | tr -d '\n' || echo "")
            if [ -n "$RUSTDESK_ID" ]; then
                echo -e "  ID: ${GREEN}${RUSTDESK_ID}${NC}"
            else
                echo "  ID: Not yet available"
            fi
        fi

        echo "  Server: openapi.mintt.cloud"
        echo "  Protocol: WebSocket (port 443)"

        echo ""
        echo "Recent logs:"
        journalctl -u rustdesk.service -n 5 --no-pager 2>/dev/null || echo "  No logs available"
    else
        echo "RustDesk is currently stopped."
        echo "To start: myisactl rustdesk-start"
    fi
}

# Main function
main() {
    case "${1:-help}" in
        "enable-staging")
            enable_staging
            ;;
        "enable-production")
            enable_production
            ;;
        "status")
            show_status
            ;;
        "sync")
            sync_packages
            ;;
        "upgrade")
            upgrade_system
            ;;
        "check")
            check_upgrade
            ;;
        "setup-repo")
            setup_repo
            ;;
        "rustdesk-start")
            rustdesk_start
            ;;
        "rustdesk-stop")
            rustdesk_stop
            ;;
        "rustdesk-status")
            rustdesk_status
            ;;
        "help"|"-h"|"--help")
            show_help
            ;;
        *)
            echo -e "${RED}❌ Unknown command: $1${NC}"
            echo ""
            show_help
            exit 1
            ;;
    esac
}

# Check if script is run as root
if [ "$EUID" -ne 0 ]; then
    echo -e "${RED}❌ This script must be run as root${NC}"
    echo "Use: sudo myisactl [COMMAND]"
    exit 1
fi

# Execute main function
main "$@"