#!/bin/bash

# Check if reset is needed
if [ ! -f /var/lib/rustdesk-needs-reset ]; then
    exit 0
fi

LOG_FILE="/home/stellarmate/.local/share/rustdesk-reset/desktop.log"
mkdir -p "$(dirname "$LOG_FILE")"

{
    echo "=== RustDesk Desktop Reset started at $(date) ==="
    echo "User: $(whoami)"
    echo "Display: $DISPLAY"

    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: $OS_TYPE"

    # Small delay to ensure desktop is fully loaded
    sleep 5

    echo "Killing rustdesk..."
    killall rustdesk 2>/dev/null || echo "No rustdesk to kill"
    sleep 2
    killall -9 rustdesk 2>/dev/null || true
    sleep 1

    echo "Starting rustdesk..."
    if [[ "$OS_TYPE" == "debian_ubuntu" ]]; then
        sudo runuser -l stellarmate -c "rustdesk &"
    elif [[ "$OS_TYPE" == "arch" ]]; then
        sudo -u stellarmate rustdesk &
    fi
    RUSTDESK_PID=$!
    echo "RustDesk PID: $RUSTDESK_PID"

    sleep 5

    if ps -p $RUSTDESK_PID > /dev/null 2>&1; then
        echo "RustDesk is running"
    else
        echo "WARNING: RustDesk died"
    fi

    echo "Resetting RustDesk password..."
    sudo rustdesk --password stellar@Mate123!
    
    echo "Stopping RustDesk..."
    sudo pkill rustdesk
    if systemctl is-active --quiet rustdesk; then
        sudo systemctl stop rustdesk 2>/dev/null
    fi
    sudo systemctl disable rustdesk 2>/dev/null

    sleep 2

    echo "Cleanup..."
    kill $RUSTDESK_PID 2>/dev/null || true
    killall -9 rustdesk 2>/dev/null || true

    echo "Removing marker..."
    sudo rm -f /var/lib/rustdesk-needs-reset

    echo "Removing autostart entry..."
    rm -f /home/stellarmate/.config/autostart/rustdesk-reset.desktop

    echo "=== Complete at $(date) ==="

    # Show notification
    notify-send "StellarMate" "RustDesk password has been reset to default"

} >> "$LOG_FILE" 2>&1
