#!/bin/bash

# Proxmox Auto-Fix Subscription Notice Script
# This script automatically checks and fixes the subscription notice using Logic Inversion method
# Designed to run at every boot to handle updates that overwrite proxmoxlib.js
# Now includes automatic service installation if missing

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

# Function to print colored output
print_status() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

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

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

print_step() {
    echo -e "${BLUE}[STEP]${NC} $1"
}

print_notice() {
    echo -e "${CYAN}[NOTICE]${NC} $1"
}

# Configuration
PROXMOX_JS_FILE="/usr/share/javascript/proxmox-widget-toolkit/proxmoxlib.js"
BACKUP_FILE="/usr/share/javascript/proxmox-widget-toolkit/proxmoxlib.js.original"
LOG_FILE="/var/log/proxmox-subscription-autofix.log"
LOCK_FILE="/tmp/proxmox-subscription-fix.lock"
SERVICE_NAME="proxmox-subscription-autofix"
SERVICE_FILE="/etc/systemd/system/${SERVICE_NAME}.service"

# Function to log with timestamp
log_message() {
    echo "$(date '+%Y-%m-%d %H:%M:%S'): $1" >> "$LOG_FILE"
}

# Function to cleanup and exit
cleanup() {
    [[ -f "$LOCK_FILE" ]] && rm -f "$LOCK_FILE"
    exit $1
}

# Set trap for cleanup
trap 'cleanup 1' INT TERM

# Start logging
log_message "=== Starting Proxmox Subscription Auto-Fix Check ==="

# Check if already running
if [[ -f "$LOCK_FILE" ]]; then
    print_warning "Another instance is already running. Exiting."
    log_message "Script already running, exiting"
    exit 0
fi

# Create lock file
echo $$ > "$LOCK_FILE"

# Check if running as root (required for file modifications and service restart)
if [[ $EUID -ne 0 ]]; then
    print_error "This script must be run as root"
    log_message "ERROR: Script not run as root"
    cleanup 1
fi

# Function to create systemd service file
create_systemd_service() {
    print_step "Creating systemd service file..."
    log_message "Creating systemd service file: $SERVICE_FILE"
    
    # Create service file content
    cat > "$SERVICE_FILE" << 'EOF'
[Unit]
Description=Proxmox Subscription Notice Auto-Fix
After=network.target pveproxy.service
Wants=pveproxy.service

[Service]
Type=oneshot
ExecStart=/usr/local/bin/proxmox_subscription_autofix.sh
User=root
StandardOutput=journal
StandardError=journal
RemainAfterExit=no

[Install]
WantedBy=multi-user.target
EOF
    
    if [[ -f "$SERVICE_FILE" ]]; then
        print_status "✓ Service file created: $SERVICE_FILE"
        log_message "Service file created successfully"
        return 0
    else
        print_error "✗ Failed to create service file"
        log_message "ERROR: Failed to create service file"
        return 1
    fi
}

# Function to install current script to system location if needed
install_script_to_system() {
    local target_script="/usr/local/bin/proxmox_subscription_autofix.sh"
    
    # Check if we need to copy ourselves to the system location
    if [[ "$(realpath "$0")" != "$target_script" ]]; then
        print_step "Installing script to system location..."
        log_message "Installing script to: $target_script"
        
        if cp "$0" "$target_script"; then
            chmod +x "$target_script"
            print_status "✓ Script installed to: $target_script"
            log_message "Script installed successfully"
            return 0
        else
            print_error "✗ Failed to install script to system location"
            log_message "ERROR: Failed to install script"
            return 1
        fi
    else
        print_status "✓ Script is already in system location"
        log_message "Script already in correct location"
        return 0
    fi
}

# Function to enable and start systemd service
enable_systemd_service() {
    print_step "Enabling and configuring systemd service..."
    log_message "Enabling systemd service: $SERVICE_NAME"
    
    # Reload systemd daemon
    if systemctl daemon-reload; then
        print_status "✓ Systemd daemon reloaded"
        log_message "Systemd daemon reloaded"
    else
        print_error "✗ Failed to reload systemd daemon"
        log_message "ERROR: Failed to reload systemd daemon"
        return 1
    fi
    
    # Enable service for automatic startup
    if systemctl enable "$SERVICE_NAME.service"; then
        print_status "✓ Service enabled for automatic startup"
        log_message "Service enabled successfully"
        return 0
    else
        print_error "✗ Failed to enable service"
        log_message "ERROR: Failed to enable service"
        return 1
    fi
}

# Function to check and setup systemd service if needed
check_and_setup_service() {
    print_step "Checking systemd service setup..."
    
    # Check if service file exists
    if [[ ! -f "$SERVICE_FILE" ]]; then
        print_warning "⚠ Systemd service file not found"
        print_status "Setting up automatic service installation..."
        log_message "Service file missing, creating it"
        
        # Install script to system location first
        if install_script_to_system; then
            # Create service file
            if create_systemd_service; then
                # Enable service
                if enable_systemd_service; then
                    print_status "✅ Systemd service installed and enabled successfully!"
                    log_message "Service setup completed successfully"
                else
                    print_warning "Service created but failed to enable"
                    log_message "Service created but enabling failed"
                fi
            else
                print_error "Failed to create service file"
                log_message "Service creation failed"
                return 1
            fi
        else
            print_error "Failed to install script to system location"
            log_message "Script installation failed"
            return 1
        fi
    else
        # Service file exists, check if it's enabled
        if systemctl is-enabled "$SERVICE_NAME.service" >/dev/null 2>&1; then
            print_status "✓ Systemd service is already installed and enabled"
            log_message "Service already properly configured"
        else
            print_warning "⚠ Service file exists but not enabled, enabling it..."
            log_message "Service exists but not enabled, enabling"
            enable_systemd_service
        fi
    fi
}

# Check if Proxmox file exists
if [[ ! -f "$PROXMOX_JS_FILE" ]]; then
    print_error "Proxmox file not found: $PROXMOX_JS_FILE"
    log_message "ERROR: Proxmox file not found"
    cleanup 1
fi

# Check and setup systemd service first
check_and_setup_service

print_status "Checking Proxmox subscription notice status..."
log_message "Starting subscription notice check"

# Function to check if Logic Inversion is already applied
check_logic_inversion() {
    local file="$1"
    # Look for the inverted logic pattern: == 'active' instead of !== 'active'
    if grep -q "\.data\.status\.toLowerCase() == 'active'" "$file"; then
        return 0  # Logic inversion is applied
    else
        return 1  # Logic inversion is NOT applied
    fi
}

# Function to check if original logic exists (needs fixing)
check_original_logic() {
    local file="$1"
    # Look for the original logic pattern: !== 'active'
    if grep -q "\.data\.status\.toLowerCase() !== 'active'" "$file"; then
        return 0  # Original logic found (needs fixing)
    else
        return 1  # Original logic not found
    fi
}

# Function to apply Logic Inversion method
apply_logic_inversion() {
    local file="$1"
    local backup_file="$2"
    
    print_step "Creating backup before modification..."
    if cp "$file" "$backup_file"; then
        print_status "✓ Backup created: $backup_file"
        log_message "Backup created successfully"
    else
        print_error "✗ Failed to create backup"
        log_message "ERROR: Backup creation failed"
        return 1
    fi
    
    print_step "Applying Logic Inversion method..."
    # Replace !== 'active' with == 'active' to invert the subscription check logic
    if sed -i "s/\.data\.status\.toLowerCase() !== 'active'/.data.status.toLowerCase() == 'active'/g" "$file"; then
        print_status "✓ Logic Inversion applied successfully"
        log_message "Logic Inversion applied successfully"
        return 0
    else
        print_error "✗ Failed to apply Logic Inversion"
        log_message "ERROR: Logic Inversion failed"
        # Restore backup
        cp "$backup_file" "$file"
        return 1
    fi
}

# Function to restart Proxmox web service
restart_proxmox_service() {
    print_step "Restarting Proxmox web service..."
    if systemctl restart pveproxy.service; then
        print_status "✓ Proxmox web service restarted successfully"
        log_message "pveproxy service restarted successfully"
        return 0
    else
        print_error "✗ Failed to restart Proxmox web service"
        log_message "ERROR: pveproxy service restart failed"
        return 1
    fi
}

# Main logic
NEEDS_FIX=false

# Check current status
if check_logic_inversion "$PROXMOX_JS_FILE"; then
    print_status "✓ Logic Inversion is already applied - subscription notice is disabled"
    log_message "Logic Inversion already applied, no action needed"
elif check_original_logic "$PROXMOX_JS_FILE"; then
    print_warning "⚠ Original logic detected - subscription notice is active"
    print_status "Need to apply Logic Inversion fix..."
    log_message "Original logic detected, fix needed"
    NEEDS_FIX=true
else
    print_notice "? Unknown state detected in proxmoxlib.js"
    print_status "File may have been modified by update or other means"
    log_message "Unknown state detected, attempting fix anyway"
    NEEDS_FIX=true
fi

# Apply fix if needed
if [[ "$NEEDS_FIX" == true ]]; then
    print_step "Applying Logic Inversion fix..."
    
    if apply_logic_inversion "$PROXMOX_JS_FILE" "$BACKUP_FILE"; then
        # Verify the fix was applied correctly
        if check_logic_inversion "$PROXMOX_JS_FILE"; then
            print_status "✅ Logic Inversion fix applied and verified successfully!"
            log_message "Fix applied and verified successfully"
            
            # Restart service to apply changes
            if restart_proxmox_service; then
                print_status "🎉 Proxmox subscription notice has been disabled automatically!"
                log_message "Complete success - subscription notice disabled"
            else
                print_warning "Fix applied but service restart failed"
                log_message "Fix applied but service restart failed"
            fi
        else
            print_error "❌ Fix application failed - verification unsuccessful"
            log_message "ERROR: Fix verification failed"
            cleanup 1
        fi
    else
        print_error "❌ Failed to apply Logic Inversion fix"
        log_message "ERROR: Fix application failed"
        cleanup 1
    fi
else
    print_status "✅ No action needed - subscription notice is already disabled"
    log_message "No action needed"
fi

# Final status report
print_notice "=== AUTO-FIX SUMMARY ==="
if check_logic_inversion "$PROXMOX_JS_FILE"; then
    print_status "Current Status: SUBSCRIPTION NOTICE DISABLED ✅"
    print_status "Logic Inversion: ACTIVE"
    log_message "Final status: Subscription notice disabled"
else
    print_error "Current Status: SUBSCRIPTION NOTICE ACTIVE ❌"
    print_error "Logic Inversion: NOT APPLIED"
    log_message "Final status: Subscription notice still active"
fi

# Show service status
if systemctl is-enabled "$SERVICE_NAME.service" >/dev/null 2>&1; then
    print_status "Systemd Service: ENABLED ✅"
    log_message "Service is enabled for automatic startup"
else
    print_warning "Systemd Service: NOT ENABLED ⚠"
    log_message "Service is not enabled"
fi

print_status "Log file: $LOG_FILE"
print_notice "Next boot will automatically run this check again"
log_message "=== Auto-fix check completed ==="

cleanup 0
