#!/bin/bash

# StellarMate Root Access Management Script
# Manages atomic updates by enabling/disabling direct pacman access

STATE_FILE="/etc/stellarmate/.root-access-state"
PACMAN_BACKUP="/etc/pacman.conf.atomic-backup"
PACMAN_CONF="/etc/pacman.conf"

# Check for root privileges
if [[ $EUID -ne 0 ]]; then
   echo "This script must be run as root"
   exit 1
fi

# Function to get current state
get_state() {
    if [[ -f "$STATE_FILE" ]]; then
        cat "$STATE_FILE"
    else
        echo "enabled"
    fi
}

# Function to show status
show_status() {
    local state=$(get_state)
    echo "================================ STATUS ================================="
    echo ""
    if [[ "$state" == "disabled" ]]; then
        echo "  Atomic Updates: DISABLED"
        echo "  Direct pacman access: ENABLED"
        echo "  sm-integrity-check: DISABLED"
        echo ""
        if [[ -f "$PACMAN_BACKUP" ]]; then
            echo "  Backup available: YES ($PACMAN_BACKUP)"
        else
            echo "  Backup available: NO"
        fi
    else
        echo "  Atomic Updates: ENABLED"
        echo "  Direct pacman access: DISABLED"
        echo "  sm-integrity-check: ENABLED"
    fi
    echo ""
    echo "========================================================================="
}

# Function to disable atomic updates (enable root access)
disable_atomic() {
    local state=$(get_state)
    
    if [[ "$state" == "disabled" ]]; then
        echo "Atomic updates are already disabled."
        echo "Run with --status to see current state."
        exit 0
    fi
    
    # Display warning
    echo "================================ WARNING ================================"
    echo ""
    echo "  This operation will modify your StellarMate OS system configuration"
    echo "  to allow direct package installation via pacman."
    echo ""
    echo "  IMPORTANT:"
    echo "  • This may make your system UNSTABLE"
    echo "  • This VOIDS your StellarMate warranty"
    echo "  • This disables the delta updater system for automatic updates"
    echo "  • You will be responsible for managing system updates manually"
    echo ""
    echo "  Only proceed if you understand the implications and need direct"
    echo "  package management access for development purposes."
    echo ""
    echo "  You can restore atomic updates later by running:"
    echo "  sudo $0 --enable"
    echo ""
    echo "========================================================================="
    echo ""
    read -p "Do you want to continue? Type 'YES' (all caps) to proceed: " confirmation

    if [[ "$confirmation" != "YES" ]]; then
        echo "Operation cancelled."
        exit 0
    fi

    echo ""
    echo "Proceeding with admin access configuration..."
    echo ""

    # Create backup directory if it doesn't exist
    mkdir -p "$(dirname "$STATE_FILE")"
    
    # Backup pacman.conf
    echo "Creating backup of /etc/pacman.conf..."
    cp "$PACMAN_CONF" "$PACMAN_BACKUP"
    
    echo "Disabling sm-integrity-check..."
    systemctl disable sm-integrity-check

    echo "Enabling Arch Linux ARM repositories in /etc/pacman.conf..."

    # Uncomment [core], [extra], and [alarm] sections
    # This handles optional spaces after the '#' character
    # It uncomments the section header and the following SigLevel and Server lines
    sed -i '/^#\s*\[core\]/{N;N;s/^#\s*\[core\]\n#\s*\(SigLevel.*\)\n#\s*\(Server.*\)/[core]\n\1\n\2/}' "$PACMAN_CONF"
    sed -i '/^#\s*\[extra\]/{N;N;s/^#\s*\[extra\]\n#\s*\(SigLevel.*\)\n#\s*\(Server.*\)/[extra]\n\1\n\2/}' "$PACMAN_CONF"
    sed -i '/^#\s*\[alarm\]/{N;N;s/^#\s*\[alarm\]\n#\s*\(SigLevel.*\)\n#\s*\(Server.*\)/[alarm]\n\1\n\2/}' "$PACMAN_CONF"

    # Update repos database
    pacman -Sy

    # Save state
    echo "disabled" > "$STATE_FILE"
    
    echo ""
    echo "Done. Atomic updates have been disabled."
    echo "You can now use pacman directly for package management."
    echo ""
    echo "To restore atomic updates, run: sudo $0 --enable"
}

# Function to enable atomic updates (disable root access)
enable_atomic() {
    local state=$(get_state)
    
    if [[ "$state" == "enabled" ]]; then
        echo "Atomic updates are already enabled."
        echo "Run with --status to see current state."
        exit 0
    fi
    
    # Display warning
    echo "========================= RESTORE ATOMIC UPDATES ========================"
    echo ""
    echo "  This operation will restore your StellarMate OS to use atomic updates."
    echo ""
    echo "  This will:"
    echo "  • Re-enable the sm-integrity-check service"
    echo "  • Restore the original pacman.conf configuration"
    echo "  • Disable direct pacman repository access"
    echo "  • Re-enable the delta updater system for automatic updates"
    echo ""
    echo "========================================================================="
    echo ""
    read -p "Do you want to continue? Type 'YES' (all caps) to proceed: " confirmation

    if [[ "$confirmation" != "YES" ]]; then
        echo "Operation cancelled."
        exit 0
    fi

    echo ""
    echo "Restoring atomic updates configuration..."
    echo ""

    # Check if backup exists
    if [[ ! -f "$PACMAN_BACKUP" ]]; then
        echo "ERROR: Backup file not found at $PACMAN_BACKUP"
        echo "Cannot safely restore atomic updates without backup."
        echo ""
        echo "You may need to manually restore /etc/pacman.conf or reinstall the system."
        exit 1
    fi

    echo "Re-enabling sm-integrity-check..."
    systemctl enable sm-integrity-check

    echo "Restoring /etc/pacman.conf from backup..."
    cp "$PACMAN_BACKUP" "$PACMAN_CONF"
    
    # Update state
    echo "enabled" > "$STATE_FILE"
    
    echo ""
    echo "Done. Atomic updates have been restored."
    echo "Your system is now back to using the StellarMate update system."
    echo ""
    echo "You may want to run the system updater to ensure everything is current."
}

# Main script logic
case "$1" in
    --disable)
        disable_atomic
        ;;
    --enable)
        enable_atomic
        ;;
    --status)
        show_status
        ;;
    *)
        echo "Usage: $0 [--disable|--enable|--status]"
        echo ""
        echo "  --disable  Disable atomic updates (enable direct pacman access)"
        echo "  --enable   Enable atomic updates (restore StellarMate updates)"
        echo "  --status   Show current atomic updates status"
        echo ""
        echo "Current status:"
        show_status
        exit 1
        ;;
esac
