#!/bin/bash

# Detect OS type
function detect_os_type() {
    local OS_TYPE="unknown"
    if [ -f /etc/os-release ]; then
        . /etc/os-release
        if [[ "$ID" == "arch" ]] || [[ "$ID_LIKE" == *"arch"* ]]; then
            OS_TYPE="arch"
        else
            OS_TYPE="debian_ubuntu"
        fi
    fi
    echo "$OS_TYPE"
}

# Reset RustDesk configuration
function reset_rustdesk() {
    echo "Scheduling RustDesk password reset for first desktop login..."

    # Stop RustDesk
    pkill -9 rustdesk 2>/dev/null || true
    sleep 1

    # Optional: Clear config for fresh ID (uncomment if needed for unique IDs per unit)
    # rm -rf /home/stellarmate/.config/rustdesk
    # mkdir -p /home/stellarmate/.config/rustdesk
    # chown -R stellarmate:stellarmate /home/stellarmate/.config/rustdesk

    # Create marker file
    touch /var/lib/rustdesk-needs-reset

    # Create autostart entry
    mkdir -p /home/stellarmate/.config/autostart
    cat > /home/stellarmate/.config/autostart/rustdesk-reset.desktop << 'EOFDESK'
[Desktop Entry]
Type=Application
Name=RustDesk Password Reset
Exec=/usr/bin/rustdesk-reset-desktop.sh
Hidden=false
NoDisplay=true
X-GNOME-Autostart-enabled=true
X-KDE-autostart-after=panel
EOFDESK

    chown -R stellarmate:stellarmate /home/stellarmate/.config/autostart

    # Disable RustDesk service temporarily
    systemctl disable rustdesk 2>/dev/null || true

    echo "RustDesk will be reset on next desktop login"
}

# Change system hostname
function reset_hostname() {
    local hostname=${1:-stellarmate}
    echo "Changing hostname to: $hostname"
    /etc/stellarmate/change-hostname.sh "$hostname"
}

# Reset network configuration
function reset_network() {
    echo "Resetting network configuration..."
    /etc/stellarmate/reset-wifi.sh
}

# Reset GPS settings
function reset_gps() {
    echo "Resetting GPS settings..."
    sed -i 's|DEVICES=.*|DEVICES="/dev/gps"|' /etc/default/gpsd
}

# Clean user application directories
function clean_user_app_directories() {
    echo "Cleaning user application directories..."
    
    # INDI
    rm -rf /home/stellarmate/.indi/* || true
    mkdir -p /home/stellarmate/.indi/logs
    
    # KStars
    rm -rf /home/stellarmate/.local/share/kstars/* || true
    mkdir -p /home/stellarmate/.local/share/kstars/logs
    
    # PHD2
    rm -rf /home/stellarmate/PHD2 || true
    rm -rf /home/stellarmate/phd* || true
    rm -rf /home/stellarmate/.phd2 || true
    
    # Cache and temporary files
    rm -rf /home/stellarmate/.cache/* || true
    rm -rf /home/stellarmate/.nano/* || true
}

# Clean user data directories
function clean_user_data_directories() {
    echo "Removing pictures and downloads..."
    rm -rf /home/stellarmate/Pictures/*
    rm -rf /home/stellarmate/Documents/*
    rm -rf /home/stellarmate/Downloads/*
}

# Reset EkosLive database
function reset_ekoslive() {
    echo "Resetting EkosLive..."
    rm -rf /home/stellarmate/.local/share/ekoslive/*
    cp /etc/stellarmate/ekoslive.db /home/stellarmate/.local/share/ekoslive/
    chown -R stellarmate:stellarmate /home/stellarmate/.local/share/ekoslive/
}

# Clean system temporary files
function clean_system_temp_files() {
    echo "Cleaning system temporary files..."
    
    local OS_TYPE=$(detect_os_type)
    
    # Distribution-specific cleanup
    if [ "$OS_TYPE" == "debian_ubuntu" ]; then
        rm -f /etc/apt/*.save || true
        rm -f /etc/apt/sources.list.d/*.save || true
    fi
    
    # Common temporary files
    rm -f /etc/resolvconf/resolv.conf.d/original
    rm -f /run/*/*pid || true
    rm -f /run/*pid || true
    rm -f /run/cups/cups.sock || true
    rm -f /run/uuidd/request || true
    rm -rf /tmp/*
    rm -f /var/crash/*
    rm -f /var/lib/urandom/random-seed
}

# Clean log files
function clean_logs() {
    echo "Clearing logs..."
    
    # Remove old compressed and rotated logs
    find /var/log -type f -name '*.gz' -delete
    find /var/log -type f -name '*.1' -delete
    find /var/log -type f -name '*.old' -delete
    
    # Clear user activity logs
    rm -rf /home/stellarmate/.local/share/recently-user.xbel
    rm -rf /home/stellarmate/.bash_history
    
    # Vacuum systemd journal
    journalctl --vacuum-size=1M
}

# Restore default configuration files
function restore_config_files() {
    echo "Restoring default configuration files..."
    
    cp /etc/stellarmate/environment /etc/environment
    cp /etc/stellarmate/rules/99-gpsd.rules /etc/udev/rules.d/
    cp /etc/stellarmate/rules/99-eth0.rules /etc/udev/rules.d/
    cp /etc/stellarmate/rules/99-stellarmate-hardware.rules /etc/udev/rules.d/
    cp /etc/stellarmate/smb.conf /etc/samba/
}

# Reset system settings
function reset_system_settings() {
    echo "Resetting system settings..."
    
    # Reset timezone to UTC
    timedatectl set-timezone UTC
    
    # Remove backup modules
    rm -rf /lib/modules.bak || true
}

# Reset pacman keys and sync databases
function reset_pacman_keys() {
    local OS_TYPE=$(detect_os_type)
    if [ "$OS_TYPE" == "arch" ]; then
        echo "Resetting pacman keys and syncing databases..."
        # Remove the stale sync databases and their signatures
        rm -rf /var/lib/pacman/sync/*

        # Now re-init keyring and sync fresh
        pacman-key --init
        pacman-key --populate
        pacman -Sy
    fi
}

# Clean package manager cache
function clean_package_cache() {
    echo "Cleaning package manager cache..."
    
    local OS_TYPE=$(detect_os_type)
    
    if [ "$OS_TYPE" == "debian_ubuntu" ]; then
        apt-get clean
    elif [ "$OS_TYPE" == "arch" ]; then
        yes | pacman -Scc
    fi
}

# Reset KDE wallet
function reset_wallet() {
    echo "Clearing wallet..."
    /etc/stellarmate/reset-wallet.sh
}

# Reset machine ID
function reset_machine_id() {
    echo "Clearing machine ID..."
    truncate -s 0 /etc/machine-id /var/lib/dbus/machine-id
}

# Main function to perform complete factory reset
function perform_common_reset() {
    local hostname=${1:-stellarmate}
    
    echo "====================================="
    echo "Starting StellarMate Factory Reset"
    echo "====================================="
    
    # Reset remote access
    reset_rustdesk
    
    # Reset system identification
    reset_hostname "$hostname"
    
    # Reset network and connectivity
    reset_network
    reset_gps
    
    # Clean application data
    clean_user_app_directories
    clean_user_data_directories
    reset_ekoslive
    
    # Clean system files
    clean_system_temp_files
    clean_logs
    
    # Restore configurations
    restore_config_files
    reset_system_settings
    
    # Reset pacman keys
    reset_pacman_keys

    # Clean package cache
    clean_package_cache
    
    # Reset security
    reset_wallet
    
    # Reset machine ID (do this late in the process)
    reset_machine_id
    
    echo "====================================="
    echo "Factory Reset Complete"
    echo "====================================="
}
