#!/bin/bash
set -e

VERSION_FILE_PATH="/opt/IDriveForLinux/idriveIt/cache/version"
REQUIRED_VERSION="1.8.0"
SYMLINK_PATH="/usr/local/bin/idriveforlinux"
checkUpdate=false
checkNetwork=false
SOURCE_FILE="/opt/IDriveForLinux/resources/app.asar.unpacked/readme.docx"
TARGET_DIRECTORY="/opt/IDriveForLinux"

pkg_manager=""
pkg_folder="rpm"
installCommand="sudo dnf reinstall -y ./IDriveForLinux.rpm"

# Watchdog timeout (seconds) for file manager kill operations
WATCHDOG_TIMEOUT=5

# Detect package manager
detectPackageManager() {
    if command -v dnf &>/dev/null; then
        pkg_manager="dnf"
    elif command -v yum &>/dev/null; then
        pkg_manager="yum"
    elif command -v zypper &>/dev/null; then
        pkg_manager="zypper"
    elif command -v apt-get &>/dev/null; then
        pkg_manager="apt-get"
        pkg_folder="deb"
        installCommand="sudo apt install --reinstall ./IDriveForLinux.deb"
    else
        echo "Warning: No supported package manager found (dnf/yum/zypper)"
        return 1
    fi

    echo "Detected package manager: $pkg_manager"
}

# Function to check if the current version matches the required version
checkVersion() {
    updateRequired=false  # Default to no update

    if [ -f "$VERSION_FILE_PATH" ]; then
        # Read the current version and trim any whitespace
        currentVersion=$(<"$VERSION_FILE_PATH" tr -d '[:space:]')

        # Check if the current version matches the required version
        if [ "$currentVersion" != "$REQUIRED_VERSION" ]; then
            echo "Updating to version: $REQUIRED_VERSION..."
            updateRequired=true
        fi
    else
        # Check if remnants of an old install exist
        if [ -d "/opt/IDriveForLinux/bin/idrive" ] && [ -d "/opt/IDriveForLinux/idriveIt" ] && [ -f "/opt/IDriveForLinux/AppVersion" ]; then
            echo "Updating to version: $REQUIRED_VERSION..."
            updateRequired=true
        else
            updateRequired=false
        fi
    fi
}

# Function to create a symbolic link for easy access if not already present
createSymlink() {
    if [ ! -e "$SYMLINK_PATH" ]; then
        ln -s /opt/IDriveForLinux/idriveforlinux "$SYMLINK_PATH" > /dev/null 2>&1
    fi
}

# Function to create or update the AppVersion file
create_version_file() {
    local FILE_NAME="/opt/IDriveForLinux/AppVersion"
    local CONSTANT_VERSION="1.8.0"
    echo "$CONSTANT_VERSION" > "$FILE_NAME"
}

# Function to run the update process
runUpdateCommand() {
    updateCommand="/opt/IDriveForLinux/resources/app.asar.unpacked/IdriveForLinux/idriveforlinux.bin --update silent"
    sandboxChownCommand="chown root:root /opt/IDriveForLinux/chrome-sandbox"
    sandboxChmodCommand="chmod 4755 /opt/IDriveForLinux/chrome-sandbox"
    logFile="/opt/IDriveForLinux/installation.txt"

    current_pid=$$
    pids=$(ps aux | grep /opt/IDriveForLinux/idriveforlinux | grep -v grep | grep -v "$current_pid" | awk '{print $2}' || true)
    # pids=$(pgrep -f "/opt/IDriveForLinux/idriveforlinux" | grep -v "$current_pid" || true)
    if [ -n "$pids" ]; then
        for pid in $pids; do
            kill -TERM "$pid" > /dev/null 2>&1 || true
        done
    fi

    # Build the command string with sandbox commands included
    command="$updateCommand && $sandboxChownCommand && $sandboxChmodCommand"

    # Execute the update command with sandbox permissions
    eval "$command" > "$logFile" 2>&1 || checkUpdate=true

    if [ "$checkUpdate" = true ]; then
        if grep -qE "(curl: \(7\) Failed to connect|curl: \(6\) Could not resolve host|Verify your network connection or proxy details|Verify your network connection and try again)" "$logFile"; then
            echo " "
            echo "*****************************************************************************"
            echo " "
            echo "IDrive update has failed. Check your network connection, and retry."
            echo " "
            echo "To retry, run the following command:"
            echo " "
            echo $installCommand
            echo " "
            echo "*****************************************************************************"
            echo " "
			updateRequired=true
        elif grep -qE "(download_failed_unable_to_download|download_failed_unable_to_extract|Unable to find the dependency packages.|Unable to download Python command line utility, check you've installed the latest package available OR contact the support team.|unable_to_extract_python|Failed to download Perl binary)" "$logFile"; then
            echo " "
            echo "*****************************************************************************"
            echo " "
            echo "IDrive update has failed.Retry."
            echo " "
            echo "To retry, run the following command:"
            echo " "
            echo $installCommand
            echo "*****************************************************************************"
            echo " "
			updateRequired=true
        fi
    else
        echo "***************************************"
        echo ""
        echo "*      IDrive Update Completed        *"
        echo ""
        echo "***************************************"
        echo ""
        echo " The application has been updated. Click the 'IDrive' icon from the Application drawer or run 'idriveforlinux' in the terminal."
        echo ""
    fi
}

# Function to run the installation process
runInstallCommand() {
    installCommand="/opt/IDriveForLinux/resources/app.asar.unpacked/IdriveForLinux/idriveforlinux.bin --install"
    sandboxChownCommand="chown root:root /opt/IDriveForLinux/chrome-sandbox"
    sandboxChmodCommand="chmod 4755 /opt/IDriveForLinux/chrome-sandbox"
    logFile="/opt/IDriveForLinux/installation.txt"

    # Build the command string with sandbox commands included
    command="$installCommand && $sandboxChownCommand && $sandboxChmodCommand"

    # Check if the user is root, otherwise run with sudo
    eval "$command" > "$logFile" 2>&1 || checkNetwork=true

    if [ "$checkNetwork" = true ]; then
        if grep -qE "(curl: \(7\) Failed to connect|curl: \(6\) Could not resolve host|Verify your network connection or proxy details|Verify your network connection and try again)" "$logFile"; then
            echo " "
            echo "*****************************************************************************"
            echo " "
            echo "IDrive installation has failed. Check your network connection,and retry."
            echo " "
            echo "To retry, run the following command:"
            echo " "
            echo $installCommand
            echo "*****************************************************************************"
            echo " "
			updateRequired=false
        elif grep -qE "(download_failed_unable_to_download|download_failed_unable_to_extract|Unable to find the dependency packages.|Unable to download Python command line utility, check you've installed the latest package available OR contact the support team.|unable_to_extract_python|Failed to download Perl binary)" "$logFile"; then
            echo " "
            echo "*****************************************************************************"
            echo " "
            echo "IDrive installation has failed.Retry installation."
            echo " "
            echo "To retry, run the following command:"
            echo " "
            echo $installCommand
            echo "*****************************************************************************"
            echo " "
			updateRequired=false
        fi
    else
        echo " "
        echo "***************************************"
        echo " "
        echo "*    IDrive Installation completed    *"
        echo " "
        echo "***************************************"
        echo "                                      "
        echo " To open the application, click the 'IDrive' icon from the Application drawer or run 'idriveforlinux' in the terminal."
        echo "                                      "
    fi
}

# Helper: send SIGTERM then SIGKILL to a named process, with a hard watchdog
# so the installer never blocks even if the process is in an uninterruptible state.
kill_process_with_watchdog() {
    local proc_name="$1"

    # Guard pgrep itself against hangs
    if ! timeout "$WATCHDOG_TIMEOUT" pgrep -x "$proc_name" > /dev/null 2>&1; then
        return 0  # Not running, or pgrep timed out — either way, move on
    fi

    echo "Restarting $proc_name..."

    # Run SIGTERM + SIGKILL in a background subshell
    (
        pkill -x "$proc_name" 2>/dev/null || true
        sleep 1
        pkill -9 -x "$proc_name" 2>/dev/null || true
    ) &
    local KILL_PID=$!

    # Watchdog: forcibly kill the subshell if it outlives the timeout
    (
        sleep "$WATCHDOG_TIMEOUT"
        if kill -0 "$KILL_PID" 2>/dev/null; then
            kill -9 "$KILL_PID" 2>/dev/null || true
        fi
    ) &
    local WATCHDOG_PID=$!

    # Wait for the kill subshell (or the watchdog to terminate it)
    wait "$KILL_PID" 2>/dev/null || true

    # Clean up the watchdog
    kill "$WATCHDOG_PID" 2>/dev/null || true
    wait "$WATCHDOG_PID" 2>/dev/null || true
}

copy_file() {
    if [[ ! -f "$SOURCE_FILE" ]]; then
        return
    fi

    cp "$SOURCE_FILE" "$TARGET_DIRECTORY"
}

set_resources_permissions() {
    local resources_dir="/opt/IDriveForLinux/resources"

    # Determine installing user (still kept for potential logging/debug)
    owner=$(detect_install_user) || exit 1
    # local owner=""
    # if [[ -n "$SUDO_USER" && "$SUDO_USER" != "root" ]]; then
    #     owner="$SUDO_USER"
    # elif [[ -n "$PKEXEC_UID" ]]; then
    #     owner=$(getent passwd "$PKEXEC_UID" | cut -d: -f1)
    # elif command -v loginctl &>/dev/null; then
    #     owner=$(loginctl list-sessions 2>/dev/null | awk '$1 ~ /^[0-9]+$/ {print $1}' | while read session; do
    #         user=$(loginctl show-session "$session" -p User --value)
    #         uid=$(id -u "$user" 2>/dev/null)
    #         if [[ "$uid" -ge 1000 ]]; then
    #             echo $(id -un "$uid")
    #             break
    #         fi
    #     done)
    # else
    #     owner=$(logname 2>/dev/null || who | awk 'NR==1{print $1}' || getent passwd 1000 | cut -d: -f1)
    # fi

    # if [[ -z "$owner" || "$owner" == "root" ]]; then
    #     echo "[ERROR] Could not determine a valid non-root user." >&2
    # else
    #     echo "[INFO] Installer user detected: $owner"
    # fi

    if [ ! -d "$resources_dir" ]; then
        echo "[WARN] Resources directory not found: $resources_dir" >&2
        return 1
    fi

    # Set permissions (no ownership change)
    chmod 750 "$resources_dir"
    find "$resources_dir" -type d -exec chmod 750 {} \;
    find "$resources_dir" -type f -exec chmod 640 {} \;
}


setup_idrive_wrapper_and_symlink() {
    local install_dir="/opt/IDriveForLinux"
    local binary_name="idriveforlinux"
    local real_binary_name="idriveforlinux-bin"
    local binary_path="$install_dir/$binary_name"
    local real_binary_path="$install_dir/$real_binary_name"
    local symlink_path="/usr/local/bin/$binary_name"
    local desktop_file="/usr/share/applications/idriveforlinux.desktop"
    local log_file="/var/log/idrive_wrapper_setup.log"

    # Determine install user (non-root who ran sudo) or fallback to UID 1000 user
    install_user=$(detect_install_user) || exit 1

    # # If script is run via sudo, this is the most accurate
    # if [[ -n "$SUDO_USER" && "$SUDO_USER" != "root" ]]; then
    #     install_user="$SUDO_USER"

    # # If run via pkexec (GUI privilege escalation)
    # elif [[ -n "$PKEXEC_UID" ]]; then
    #     install_user=$(getent passwd "$PKEXEC_UID" | cut -d: -f1)

    # # Try to detect the currently active graphical user (loginctl method)
    # elif command -v loginctl &>/dev/null; then
    #     install_user=$(loginctl list-sessions 2>/dev/null | awk '$1 ~ /^[0-9]+$/ {print $1}' | while read session; do
    #         user=$(loginctl show-session "$session" -p Name --value)
    #         active=$(loginctl show-session "$session" -p Active --value)
    #         seat=$(loginctl show-session "$session" -p Seat --value)
    #         if [[ "$active" == "yes" && "$seat" == "seat0" ]]; then
    #             echo "$user"
    #             break
    #         fi
    #     done)

    # # Fallbacks for terminal environments (without GUI sessions)
    # else
    #     install_user=$(logname 2>/dev/null || who | awk 'NR==1{print $1}' || getent passwd 1000 | cut -d: -f1)
    # fi


    # Check if real binary already exists
    if [[ ! -f "$real_binary_path" ]]; then
        if [[ ! -f "$binary_path" ]]; then
            echo "[ERROR] Binary not found at $binary_path" | tee -a "$log_file"
            return 1
        fi

        mv "$binary_path" "$real_binary_path" || {
            echo "[ERROR] Failed to move binary." | tee -a "$log_file"
            return 1
        }

        # Safely chown only if user exists
        if id "$install_user" &>/dev/null; then
            chown "$install_user:$install_user" "$real_binary_path"
        fi

        # Create the wrapper script
        cat <<EOF > "$binary_path"
#!/bin/bash

real_binary="$real_binary_path"
INSTALL_USER=\$(stat -c '%U' "\$real_binary")
CURRENT_USER=\$(whoami)

if [[ "\$CURRENT_USER" != "\$INSTALL_USER" ]]; then
    if command -v notify-send &>/dev/null; then
        notify-send -t 15000 "IDrive" "This app was installed by \$INSTALL_USER. Please switch to that profile to run the application."
    else
        echo "This app was installed by \$INSTALL_USER. Please switch to that profile to run the application."
    fi
    exit 1
fi

exec "\$real_binary" "\$@"
EOF

        chmod +x "$binary_path"
    fi

    # Ensure wrapper is owned by root
    chown root:root "$binary_path"

    # Create symlink
    ln -sf "$binary_path" "$symlink_path"

    # Update system .desktop file
    if [[ -f "$desktop_file" ]]; then
        sed -i "s|^Exec=.*|Exec=$symlink_path|" "$desktop_file"
    fi
}

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
}

set_permissions_and_ownership() {
    INSTALL_DIR="/opt/IDriveForLinux"
    install_user=$(detect_install_user) || exit 1

    # # If script is run via sudo, this is the most accurate
    # if [[ -n "$SUDO_USER" && "$SUDO_USER" != "root" ]]; then
    #     install_user="$SUDO_USER"

    # # If run via pkexec (GUI privilege escalation)
    # elif [[ -n "$PKEXEC_UID" ]]; then
    #     install_user=$(getent passwd "$PKEXEC_UID" | cut -d: -f1)

    # # Try to detect the currently active graphical user (loginctl method)
    # elif command -v loginctl &>/dev/null; then
    #     install_user=$(loginctl list-sessions 2>/dev/null | awk '$1 ~ /^[0-9]+$/ {print $1}' | while read session; do
    #         user=$(loginctl show-session "$session" -p Name --value)
    #         active=$(loginctl show-session "$session" -p Active --value)
    #         seat=$(loginctl show-session "$session" -p Seat --value)
    #         if [[ "$active" == "yes" && "$seat" == "seat0" ]]; then
    #             echo "$user"
    #             break
    #         fi
    #     done)

    # # Fallbacks for terminal environments (without GUI sessions)
    # else
    #     install_user=$(logname 2>/dev/null || who | awk 'NR==1{print $1}' || getent passwd 1000 | cut -d: -f1)
    # fi


    # if [[ -z "$install_user" ]]; then
    #     echo "Could not detect installing user. Exiting."
    #     return 1
    # fi

    install_group=$(id -gn "$install_user")

    # Step 2: Apply folder ownership
    chown "$install_user:root" "$INSTALL_DIR"
    chmod 755 "$INSTALL_DIR"

    # Step 3: Apply ownership and permissions to contents
    chown "$install_user:root" "$INSTALL_DIR"/*
    chown -R "$install_user:$install_user" "$INSTALL_DIR/bin"
    chown -R "$install_user:root" "$INSTALL_DIR/idriveIt"
    chown -R "$install_user:root" "$INSTALL_DIR/resources"
    chown -R "$install_user:root" "$INSTALL_DIR/locales"

    # Specific permissions
    chmod 755 "$INSTALL_DIR"
    chmod 755 "$INSTALL_DIR/chrome_crashpad_handler"
    chmod 4755 "$INSTALL_DIR/chrome-sandbox"

    chmod 750 "$INSTALL_DIR/resources"
    chmod 750 "$INSTALL_DIR/idriveIt"
    chmod 775 "$INSTALL_DIR/locales"

    chown root:root /opt/IDriveForLinux/chrome-sandbox
    chmod 4755 /opt/IDriveForLinux/chrome-sandbox

    find "$INSTALL_DIR" -type f -name "*.so" -exec chmod 755 {} \;
    find "$INSTALL_DIR" -type f -name "*.pak" -exec chmod 644 {} \;
    find "$INSTALL_DIR" -type f -name "*.json" -exec chmod 644 {} \;
    find "$INSTALL_DIR" -type f -name "*.dat" -exec chmod 644 {} \;
    find "$INSTALL_DIR" -type f -name "*.txt" -exec chmod 644 {} \;
    find "$INSTALL_DIR" -type f -name "*.html" -exec chmod 644 {} \;

    chmod 644 "$INSTALL_DIR/AppVersion" "$INSTALL_DIR/installation.txt" "$INSTALL_DIR/readme.docx"

}

python_Dependencies_install() {
    pip3 install --upgrade pip >/dev/null 2>&1
    pip3 install watchdog PyGObject >/dev/null 2>&1
}

install_file_manager_python_dependencies() {
    echo "Checking for file managers and installing Python3 dependencies..."

    local packages_to_install=()

    # Always install attr package (required for extended file attributes/overlay icons)
    packages_to_install+=("attr")

    # Package names differ between openSUSE and Fedora/RHEL
    if [ "$pkg_manager" = "zypper" ] || [ "$pkg_manager" = "apt-get" ]; then
        # openSUSE uses python3-* naming (similar to Debian)
        if command -v nautilus &>/dev/null; then
            echo "Nautilus detected, adding python3-nautilus to installation list"
            packages_to_install+=("python3-nautilus")
        fi

        if command -v nemo &>/dev/null; then
            echo "Nemo detected, adding python3-nemo to installation list"
            packages_to_install+=("python3-nemo")
        fi

        if command -v caja &>/dev/null; then
            echo "Caja detected, adding python-caja to installation list"
            if [ "$pkg_manager" = "zypper" ]; then
                packages_to_install+=("python-caja")
            else
                packages_to_install+=("python3-caja")
            fi
        fi
    else
        # Fedora/RHEL/CentOS use *-python naming
        if command -v nautilus &>/dev/null; then
            echo "Nautilus detected, adding nautilus-python to installation list"
            packages_to_install+=("nautilus-python")
        fi

        if command -v nemo &>/dev/null; then
            echo "Nemo detected, adding nemo-python to installation list"
            packages_to_install+=("nemo-python")
        fi

        if command -v caja &>/dev/null; then
            echo "Caja detected, adding python3-caja to installation list"
            packages_to_install+=("python3-caja")
        fi
    fi

    # Install packages if any were found
    if [ ${#packages_to_install[@]} -gt 0 ]; then
        echo "Installing: ${packages_to_install[*]}"

        case "$pkg_manager" in
            dnf|yum)
                # For dnf/yum (Fedora, RHEL, CentOS)
                $pkg_manager install -y --setopt=install_weak_deps=False "${packages_to_install[@]}" >/dev/null 2>&1 || {
                    echo "Warning: Some Python3 file manager dependencies failed to install"
                    echo "You may need to manually install: ${packages_to_install[*]}"
                    echo "Or enable EPEL repository if on RHEL/CentOS: dnf install epel-release"
                }
                ;;
            zypper)
                # For zypper (openSUSE)
                zypper install -y --no-recommends "${packages_to_install[@]}" >/dev/null 2>&1 || {
                    echo "Warning: Some Python3 file manager dependencies failed to install"
                    echo "You may need to manually install: ${packages_to_install[*]}"
                }
                ;;
            apt-get)
                # Update package cache
                apt-get update -qq >/dev/null 2>&1 || {
                    echo "Warning: Failed to update package cache"
                }

                # Install packages
                DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends "${packages_to_install[@]}" >/dev/null 2>&1 || {
                    echo "Warning: Some Python3 file manager dependencies failed to install"
                    echo "You may need to manually install: ${packages_to_install[*]}"
                }
                ;;    
        esac

        echo "Python3 file manager dependencies installation completed"
    else
        echo "No supported file managers (Nautilus/Nemo/Caja) detected, but installing attr package"
        # Still install attr even if no file managers detected
        case "$pkg_manager" in
            dnf|yum)
                $pkg_manager install -y attr >/dev/null 2>&1 || {
                    echo "Warning: Failed to install attr package"
                }
                ;;
            zypper)
                zypper install -y attr >/dev/null 2>&1 || {
                    echo "Warning: Failed to install attr package"
                }
                ;;
            apt-get)
                DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends attr >/dev/null 2>&1 || {
                    echo "Warning: Failed to install attr package"
                }
                ;;
        esac
    fi

    return 0
}

cleanup_cloud_sync_details() {
    INSTALL_DIR="/home/"
    install_user=$(detect_install_user) || exit 1

    CLOUD_DIR="$INSTALL_DIR/$install_user/.config/cloud-drive"

	if [ -d "$CLOUD_DIR" ]; then
        rm -rf "$CLOUD_DIR" || { echo "Failed to remove $CLOUD_DIR"; exit 1; }
    fi
    mkdir -p "$CLOUD_DIR" || { echo "Failed to create $CLOUD_DIR"; exit 1; }
	chmod 777 "$CLOUD_DIR"
}

install_nautilus_overlay_icons() {
    INSTALL_DIR="/home/"
    install_user=$(detect_install_user) || exit 1

    # Source directory for overlay icons
    local source_icon_dir="/opt/IDriveForLinux/resources/app.asar.unpacked/daemon/assets"

    # Source extension file
    local source_extension_file="/opt/IDriveForLinux/resources/app.asar.unpacked/daemon/idrive_overlay_xattr.py"

    # Destination directories for icons
    local dest_icon_dir_icons="$INSTALL_DIR/$install_user/.icons/hicolor/16x16/emblems"
    local dest_icon_dir_local="$INSTALL_DIR/$install_user/.local/share/icons/hicolor/16x16/emblems"

    # Extension directories for all three file managers
    local dest_extension_nautilus="$INSTALL_DIR/$install_user/.local/share/nautilus-python/extensions"
    local dest_extension_nemo="$INSTALL_DIR/$install_user/.local/share/nemo-python/extensions"
    local dest_extension_caja="$INSTALL_DIR/$install_user/.local/share/caja-python/extensions"

    # Check if source directory exists
    if [[ ! -d "$source_icon_dir" ]]; then
        echo "Source icon directory not found: $source_icon_dir"
        return 0
    fi

    # Create destination directories for icons
    mkdir -p "$dest_icon_dir_icons" || {
        echo "Failed to create directory: $dest_icon_dir_icons"
        return 1
    }
    mkdir -p "$dest_icon_dir_local" || {
        echo "Failed to create directory: $dest_icon_dir_local"
        return 1
    }

    # Create extension directories for all three file managers
    mkdir -p "$dest_extension_nautilus" || {
        echo "Failed to create directory: $dest_extension_nautilus"
        return 1
    }
    mkdir -p "$dest_extension_nemo" || {
        echo "Failed to create directory: $dest_extension_nemo"
        return 1
    }
    mkdir -p "$dest_extension_caja" || {
        echo "Failed to create directory: $dest_extension_caja"
        return 1
    }

    # Copy extension file to all three file managers
    cp "$source_extension_file" "$dest_extension_nautilus/" || {
        echo "Failed to copy extension to $dest_extension_nautilus/"
    }
    cp "$source_extension_file" "$dest_extension_nemo/" || {
        echo "Failed to copy extension to $dest_extension_nemo/"
    }
    cp "$source_extension_file" "$dest_extension_caja/" || {
        echo "Failed to copy extension to $dest_extension_caja/"
    }

    # Copy all SVG files from source to both icon destinations
    for svg_file in "$source_icon_dir"/*.svg; do
        if [[ -f "$svg_file" ]]; then
            cp "$svg_file" "$dest_icon_dir_icons/" || {
                echo "Failed to copy $svg_file to $dest_icon_dir_icons"
            }
            cp "$svg_file" "$dest_icon_dir_local/" || {
                echo "Failed to copy $svg_file to $dest_icon_dir_local"
            }
        fi
    done

    echo "Overlay icons and extensions installed successfully for Nautilus, Nemo, and Caja"

    # Restart file managers if they are running (guarded by a watchdog timer)
    kill_process_with_watchdog "nautilus"
    kill_process_with_watchdog "nemo"
    kill_process_with_watchdog "caja"

    return 0
}

install_dolphin_plugin() {
    # Check if dolphin is installed
    if ! command -v dolphin &>/dev/null; then
        echo "Dolphin file manager not detected. Skipping plugin installation."
        return 0
    fi

    echo "Dolphin detected. Installing icon overlay plugin..."

    # Check runtime dependencies
    local missing_deps=()
    local required_packages=''

    if [ "$pkg_manager" = "apt-get" ]; then
        required_packages=(
            "libkf5kio5"
            "libkf5coreaddons5"
            "libkf5widgetsaddons5"
            "libqt5core5a"
            "libqt5network5"
            "libqt5widgets5"
        )
        for pkg in "${required_packages[@]}"; do
            if ! dpkg -l | grep -q "^ii.*$pkg"; then
                missing_deps+=("$pkg")
            fi
        done
    else
        required_packages=(
            "kf5-kio"
            "kf5-kcoreaddons"
            "qt5-qtbase"
        )
        for pkg in "${required_packages[@]}"; do
            if ! rpm -q "$pkg" &>/dev/null; then
                missing_deps+=("$pkg")
            fi
        done
    fi

    if [ ${#missing_deps[@]} -gt 0 ]; then
        echo "Missing some runtime dependencies for Dolphin plugin: ${missing_deps[*]}"
        echo "Plugin may not work correctly. Please install: ${pkg_manager} install ${missing_deps[*]}"
        echo "Continuing with plugin installation anyway..."
    fi

    local plugin_source_dir="/opt/IDriveForLinux/resources/app.asar.unpacked/daemon/dolphin-plugin/${pkg_folder}"
    local plugin_so="$plugin_source_dir/idriveiconoverlayplugin.so"
    local plugin_json="$plugin_source_dir/idriveiconoverlayplugin.json"

    # Check if source files exist
    if [[ ! -f "$plugin_so" ]] || [[ ! -f "$plugin_json" ]]; then
        echo "Dolphin plugin files not found in $plugin_source_dir"
        return 0
    fi

    # Detect Qt5 plugin directory (RPM systems typically use /usr/lib64 on x86_64)
    local qt_plugin_dir=""
    for dir in /usr/lib/x86_64-linux-gnu/qt5/plugins /usr/lib/qt5/plugins /usr/lib64/qt5/plugins /usr/lib64/qt6/plugins /usr/lib/qt6/plugins; do
        if [[ -d "$dir" ]]; then
            qt_plugin_dir="$dir"
            break
        fi
    done

    if [[ -z "$qt_plugin_dir" ]]; then
        echo "Qt plugin directory not found. Skipping Dolphin plugin installation."
        return 0
    fi

    local target_dir="$qt_plugin_dir/kf5/overlayicon"
    mkdir -p "$target_dir"

    # Copy plugin files
    cp "$plugin_so" "$target_dir/" || {
        echo "[ERROR] Failed to copy plugin .so file"
        return 1
    }
    cp "$plugin_json" "$target_dir/" || {
        echo "[ERROR] Failed to copy plugin .json file"
        return 1
    }

    # Set proper permissions
    chmod 644 "$target_dir/idriveiconoverlayplugin.json"
    chmod 755 "$target_dir/idriveiconoverlayplugin.so"

    # Verify plugin library dependencies
    if command -v ldd &>/dev/null; then
        echo "Checking plugin library dependencies..."
        local unresolved=$(ldd "$target_dir/idriveiconoverlayplugin.so" 2>&1 | grep "not found" || true)
        if [[ -n "$unresolved" ]]; then
            echo "Plugin has unresolved library dependencies:"
            echo "$unresolved"
            echo "The plugin may not load correctly in Dolphin."
        else
            echo "All shared library dependencies resolved successfully."
        fi
    fi

    echo "IDrive Dolphin icon overlay plugin installed successfully to $target_dir"

    # Restart Dolphin to load the plugin (guarded by a watchdog timer)
    kill_process_with_watchdog "dolphin"

    return 0
}

install_valkey_or_redis() {
    # Detect OS and version
    if [ -f /etc/os-release ]; then
        . /etc/os-release
        os_id=$ID
        version_id=${VERSION_ID%%.*}  # Get major version
    else
        echo "Unsupported OS"
        exit 1
    fi

    echo "Detected OS: $os_id $version_id"

    case "$os_id" in
        fedora)
            if [ "$version_id" -ge 41 ]; then
                echo "Installing valkey (Fedora $version_id)"
                dnf install -y valkey valkey-compat || exit 1
            else
                echo "Installing redis"
                dnf install -y redis || exit 1
            fi
            ;;
        centos)
            if grep -q "CentOS Stream release 10" /etc/centos-release 2>/dev/null; then
                echo "Installing valkey (CentOS Stream 10)"
                dnf install -y valkey valkey-compat || exit 1
            else
                echo "Installing redis (CentOS)"
                dnf install -y redis redis-server || exit 1
            fi
            ;;
        rhel)
            echo "Installing redis (RHEL)"
            dnf install -y redis redis-server || exit 1
            ;;
        *)
            echo "Unsupported OS for redis/valkey"
            exit 1
            ;;
    esac
}

start_post_install_background_task() {
  SCRIPT_PATH="/opt/IDriveForLinux/resources/app.asar.unpacked/dependency_script/post-install-$pkg_folder.sh"
  if [[ -f "$SCRIPT_PATH" ]]; then
    chmod +x "$SCRIPT_PATH"
    nohup "$SCRIPT_PATH" >/dev/null 2>&1 &
    echo "Background dependency installation started (see /tmp/idrive-post-install.log)"
  else
    echo "[WARN] Script $SCRIPT_PATH not found"
  fi
}

main() {
    detectPackageManager
    checkVersion
    copy_file

    # install_file_manager_python_dependencies
    install_dolphin_plugin
    install_nautilus_overlay_icons

    # Check if an update is required based on the updateRequired flag set by checkVersion()
    if [ "$updateRequired" = true ]; then
        runUpdateCommand
    elif [ "$updateRequired" = false ]; then	
        runInstallCommand
    	cleanup_cloud_sync_details
    else
        echo "An error occurred during the version check. Exiting."
        exit 1
    fi

    #set_resources_permissions
    createSymlink
    create_version_file

    if ! [ "$pkg_manager" = "apt-get" ]; then
        python_Dependencies_install
    fi

    #install_valkey_or_redis
    #set_permissions_and_ownership
    #setup_idrive_wrapper_and_symlink

    mkdir -p /opt/IDriveForLinux/.config/cloud-drive
    echo -n 'aJF6Q4IP7IDO1moUhUHwVQ==:Y7B0vLir0nPK/saicnTvGldpsR8HoJWuc5/dVW0A0Xo=' > /opt/IDriveForLinux/.config/cloud-drive/.junk.txt
    chmod 644 /opt/IDriveForLinux/.config/cloud-drive/.junk.txt

    start_post_install_background_task
}

# Main script execution
main

exit 0
