#!/bin/bash
set -e

detect_install_user() {
    local install_user=""

    # 1. Sudo user
    if [[ -n "$SUDO_USER" && "$SUDO_USER" != "root" ]]; then
        install_user="$SUDO_USER"

    # 2. pkexec user
    elif [[ -n "$PKEXEC_UID" ]]; then
        install_user=$(getent passwd "$PKEXEC_UID" | cut -d: -f1 2>/dev/null)

    # 3. loginctl (guarded)
    elif command -v loginctl &>/dev/null; then
        while read -r session; do
            if loginctl show-session "$session" &>/dev/null; then
                user=$(loginctl show-session "$session" -p Name --value 2>/dev/null)
                active=$(loginctl show-session "$session" -p Active --value 2>/dev/null)
                state=$(loginctl show-session "$session" -p State --value 2>/dev/null)
                seat=$(loginctl show-session "$session" -p Seat --value 2>/dev/null)

                # Prefer sessions with state "active" (not just "online") and seat0
                if [[ "$state" == "active" && "$seat" == "seat0" ]]; then
                    install_user="$user"
                    break
                fi
            fi
        done < <(loginctl list-sessions 2>/dev/null | awk '{print $1}')
    fi

    # 4. Fallback: gdebi / pkexec detection
    if [[ -z "$install_user" ]]; then
        install_user=$(ps -eo uid:1,user:100,comm | grep -m1 -E "gdebi|gdebi-gtk|pkexec" | awk '{print $2}' 2>/dev/null)
    fi

    # 5. Logname fallback (safe and quoted)
    if [[ -z "$install_user" && -x "$(command -v logname)" ]]; then
        install_user=$(logname 2>/dev/null)
    fi

    # 6. Last fallback: UID >= 1000
    if [[ -z "$install_user" || "$install_user" == "root" ]]; then
        install_user=$(getent passwd | awk -F: '$3 >= 1000 && $1 != "nobody" {print $1; exit}' 2>/dev/null)
    fi

    # 7. Final sanity check
    if ! id "$install_user" &>/dev/null; then
        echo "[ERROR] Could not detect a valid non-root installing user: '$install_user'"
        return 1
    fi

    echo "$install_user"
    return 0
}

remove_dolphin_plugin() {
    #echo "[INFO] Removing Dolphin icon overlay plugin..."

    # Search for the plugin in common Qt5/Qt6 plugin directories (RPM systems)
    local qt_plugin_dirs=(
        "/usr/lib64/qt5/plugins/kf5/overlayicon"
        "/usr/lib/qt5/plugins/kf5/overlayicon"
        "/usr/lib64/qt6/plugins/kf5/overlayicon"
        "/usr/lib/qt6/plugins/kf5/overlayicon"
        "/usr/lib/x86_64-linux-gnu/qt5/plugins/kf5/overlayicon"
    )

    local plugin_removed=false
    for plugin_dir in "${qt_plugin_dirs[@]}"; do
        if [ -d "$plugin_dir" ]; then
            if [ -f "$plugin_dir/idriveiconoverlayplugin.so" ] || [ -f "$plugin_dir/idriveiconoverlayplugin.json" ]; then
                rm -f "$plugin_dir/idriveiconoverlayplugin.so" > /dev/null 2>&1 || true
                rm -f "$plugin_dir/idriveiconoverlayplugin.json" > /dev/null 2>&1 || true
                #echo "Removed Dolphin plugin from $plugin_dir"
                plugin_removed=true
            fi
        fi
    done

    #if [ "$plugin_removed" = false ]; then
        #echo "No Dolphin plugin installation found."
    #else
        #echo "Dolphin plugin removed. Please restart Dolphin if running."
    #fi
}

remove_idrive_extension_and_daemon() {
    install_user=$(detect_install_user) || return 1
    homeDir="/home/$install_user"

    paramCacheFileForDeb="$homeDir/.config/cloud-drive/idrive_overLay_param"
    pidFile="/tmp/idrive_overlay.pid"
    paramCacheFile="/tmp/idrive_overlay_param"
    dbFile="/tmp/idrive_overlay_status.db"
    overlayScript="$homeDir/.local/share/nautilus-python/extensions/idrive_overlay.py"
    overlayScriptXattr="$homeDir/.local/share/nautilus-python/extensions/idrive_overlay_xattr.py"
    extensionsDir="$homeDir/.local/share/nautilus-python/extensions"

    # Step 1: Kill daemon if running
    if [ -f "$pidFile" ]; then
        pid=$(cat "$pidFile")
        if ps -p "$pid" > /dev/null 2>&1; then
            # echo "Sending SIGTERM to daemon process $pid..."
            kill -TERM "$pid" > /dev/null 2>&1 || true

            # Wait up to 1 second for termination
            for i in {1..5}; do
                sleep 0.2
                if ! ps -p "$pid" > /dev/null 2>&1; then
                    # echo "Process $pid terminated gracefully."
                    break
                fi
            done

            # Force kill if still running
            if ps -p "$pid" > /dev/null 2>&1; then
                # echo "Force killing process $pid..."
                kill -KILL "$pid" > /dev/null 2>&1 || true
            fi
        fi
    #else
        # echo "Daemon PID file not found. Skipping daemon termination."
    fi

    # Step 2: Remove files
    rm -f "$pidFile" > /dev/null 2>&1 || true
    rm -f "$paramCacheFileForDeb" > /dev/null 2>&1 || true
    rm -f "$paramCacheFile" > /dev/null 2>&1 || true
    rm -f "$dbFile" > /dev/null 2>&1 || true

    # Step 3: Remove overlay scripts from Nautilus
    if [ -f "$overlayScript" ]; then
        rm -f "$overlayScript" > /dev/null 2>&1 || true
        #echo "Removed overlay script: $overlayScript"
    fi

    if [ -f "$overlayScriptXattr" ]; then
        rm -f "$overlayScriptXattr" > /dev/null 2>&1 || true
        # echo "Removed overlay script: $overlayScriptXattr"
    fi

    # Remove overlay scripts from Nemo
    rm -f "$homeDir/.local/share/nemo-python/extensions/idrive_overlay.py" > /dev/null 2>&1 || true
    rm -f "$homeDir/.local/share/nemo-python/extensions/idrive_overlay_xattr.py" > /dev/null 2>&1 || true

    # Remove overlay scripts from Caja
    rm -f "$homeDir/.local/share/caja-python/extensions/idrive_overlay.py" > /dev/null 2>&1 || true
    rm -f "$homeDir/.local/share/caja-python/extensions/idrive_overlay_xattr.py" > /dev/null 2>&1 || true

    # Step 4: Remove extensions directories if empty
    if [ -d "$extensionsDir" ] && [ "$(ls -A "$extensionsDir")" = "" ]; then
        rmdir "$extensionsDir" > /dev/null 2>&1 || true
        # echo "Removed empty extensions directory: $extensionsDir"
    fi

    if [ -d "$homeDir/.local/share/nemo-python/extensions" ] && [ "$(ls -A "$homeDir/.local/share/nemo-python/extensions")" = "" ]; then
        rmdir "$homeDir/.local/share/nemo-python/extensions" > /dev/null 2>&1 || true
        #echo "Removed empty Nemo extensions directory"
    fi

    if [ -d "$homeDir/.local/share/caja-python/extensions" ] && [ "$(ls -A "$homeDir/.local/share/caja-python/extensions")" = "" ]; then
        rmdir "$homeDir/.local/share/caja-python/extensions" > /dev/null 2>&1 || true
        #echo "Removed empty Caja extensions directory"
    fi
}

kill_daemon_bulk() {
    local script_path="/opt/IDriveForLinux/resources/app.asar.unpacked/daemon/daemon_bulk.py"

    # Get all PIDs matching the script path
    local pids
    pids=$(ps aux | grep "$script_path" | grep -v grep | awk '{print $2}')

    if [ -n "$pids" ]; then
        for pid in $pids; do
            kill "$pid"
        done
    fi
}

# Check if this is a removal operation
if [ "$1" = "0" ] || [ "$1" = "remove" ] || [ "$1" = "purge" ]; then  # "$1" equals 0 for removal
    #echo "Running post-uninstallation cleanup..."

    if [ "$1" = "remove" ] || [ "$1" = "purge" ]; then
        # Delete the link to the binary if it exists
        if command -v update-alternatives >/dev/null 2>&1; then
            update-alternatives --remove 'idriveforlinux' '/usr/bin/idriveforlinux' > /dev/null 2>&1 || true
        else
            rm -f '/usr/bin/idriveforlinux' > /dev/null 2>&1 || true
        fi
    fi
    # Get the PID of the current script (uninstallation process)
    current_pid=$$

    # Get all PIDs of running instances of IDriveForLinux, excluding the current script
    pids=$(ps aux | grep /opt/IDriveForLinux/idriveforlinux | grep -v grep | grep -v "$current_pid" | awk '{print $2}' || true)

    # Kill all found PIDs if any are found, otherwise continue
    if [ -n "$pids" ]; then
        for pid in $pids; do
            kill -TERM "$pid" > /dev/null 2>&1 || true
        done
    fi

    # Remove the symbolic link from /usr/local/bin if it exists
    if [ -L "/usr/local/bin/idriveforlinux" ]; then
        rm -f /usr/local/bin/idriveforlinux > /dev/null 2>&1 || true
    fi

    # Check and remove any files matching /etc/idrive*
    if ls /etc/idrive* >/dev/null 2>&1; then
        #echo "Removing /etc/idrive* files..."
        rm -f /etc/idrive* || true
    fi

    # Remove the /opt/IDriveForLinux directory if it exists
    if [ -d "/opt/IDriveForLinux" ]; then
        #echo "Removing /opt/IDriveForLinux directory..."
        rm -rf /opt/IDriveForLinux > /dev/null 2>&1 || true
    fi

    install_user=$(detect_install_user) || return 1
    homeDir="/home/$install_user"
    # Check and remove any files matching /etc/idriveforlinux.*
    if ls $homeDir/.local/share/applications/idrive-open-* >/dev/null 2>&1; then
        rm -f $homeDir/.local/share/applications/idrive-open-* || true
    fi

    # homeDir="/home/$install_user/"

    kill_daemon_bulk

    paramCacheFile="/tmp/idrive_overLay_param"

    rm -f "$paramCacheFile" > /dev/null 2>&1 || true

    # install_user=$(detect_install_user) || exit 1

    # Remove all IDrive open-folder launcher entries
    find "/home/$install_user/.local/share/applications" -type f -name "idrive-open-*.desktop" -exec rm -f {} \; || true

    # Refresh desktop database
    update-desktop-database "/home/$install_user/.local/share/applications" || true

    # Remove Dolphin plugin
    remove_dolphin_plugin

    # Remove IDrive extensions for Nautilus, Nemo, and Caja
    remove_idrive_extension_and_daemon

    # Uninstallation completion message
    echo ""
    echo "**************************************"
    echo ""
    echo "*  Uninstallation process completed  *"
    echo ""
    echo "**************************************"
    echo ""
fi

# Properly terminate the script
exit 0