#!/bin/bash

check_for_updates() {
    pkill -f "yad.*"
    local repository_path="./apps"
    local installed_scripts_path="$HOME/.linstore/installscripts"
    local updates=()

    mkdir -p "$installed_scripts_path"

    # Show progress dialog
    (
        echo "# Checking for updates"
        sleep 1

        # Clean up previous installation
        rm -rf ~/.linstore/tmp
        echo "# Cloning repository"
        git clone https://github.com/techguy16/linstore ~/.linstore/tmp
        sleep 1

        echo "# Moving apps"
        rm -rf ./apps
        mv ~/.linstore/tmp/apps ./apps
        sleep 1

        # Clean up
        rm -rf ~/.linstore/tmp
        echo "# Finished"
    ) | yad --title "Checking for Updates" --text "Checking for updates" --progress --pulsate --width=300 --enable-log="Log" --auto-kill --auto-close --no-buttons

    for installed_script in "$installed_scripts_path"/*; do
        app_name=$(basename "$installed_script")

        # Ignore specific files
        if [[ "$app_name" == "test" ]]; then
            continue
        fi

        app_directory="$repository_path/$app_name"
        app_script=$(./api whatscript "$app_directory" "$app_name")
        script="$app_directory/$app_script"

        if [ -d "$app_directory" ]; then
            needs_update=true
            if [ -e "$script" ]; then
                if diff -q "$installed_script" "$script" >/dev/null; then
                    needs_update=false
                fi
            fi

            if $needs_update; then
                icon_path="$app_directory/icon-16.png"
                updates+=(TRUE "$icon_path" "$app_name")
            fi
        else
            updates+=(FALSE "" "$app_name (No directory found)")
        fi
    done

    if [ ${#updates[@]} -eq 0 ]; then
        pkill -f "yad.*"
        yad --info --title="LinStore Updates" --text="All apps are up to date!" --width=450 --height=600
    else
        pkill -f "yad.*"
        updates_list=$(yad --list --title="LinStore Updates" --column="Select":CHK --column="Icon":IMG --column="App" \
            "${updates[@]}" --checklist --width=450 --height=600 --button="Update Selected:0" --hide-header)

        response=$?

        if [ $response -eq 0 ]; then
            IFS=$'\n' read -d '' -r -a selected_apps <<<"$updates_list"

            for selected in "${selected_apps[@]}"; do
                if [[ "$selected" == TRUE* ]]; then
                    app_name=$(echo "$selected" | cut -d '|' -f 3)
                    echo "Updating selected: $app_name" # Debug: selected app being updated
                    app_directory="$repository_path/$app_name"
                    install=$(./api install "$app_directory" "$app_name")
                    bash -c "${install}"
                fi
            done
        fi
    fi
    ./gui
}

# Call the function
check_for_updates
