#!/bin/bash

# Include scripts
scriptPath=$(dirname "${BASH_SOURCE[0]}")
. "$scriptPath/common.sh"
source ./common.sh

logFolder="${HOME}/installation"
logFile="${logFolder}/uninstall.log"
sudo touch "$logFile"
sudo chmod a+rw "$logFile"

MenuLog "$@"
DisplayEndUninstallation "N/A" "Start"

ConfirmUninstall
confirmation=$?

if [ $confirmation == 0 ]; then
    ( (

        # Make sure software is not running
        stopScripPath="/kis/app/scripts/stop-services.sh"
        if [[ -e "$stopScripPath" ]];then
            LogAndOutputToZenity "Stoping services"
            eval sudo $stopScripPath
        fi
        sudo pkill dotnet
        sudo pkill chromium-browse

        echo "======================================================================"
        echo "Saving stats + counter in /kis/backup ====================================="
        echo "======================================================================"
        LogAndOutputToZenity "Saving stats + counters in /kis/statsbackup"
        Backup

        echo "======================================================================"
        echo "REMOVING PACKAGES ===================================================="
        echo "======================================================================"
        LogAndOutputToZenity "REMOVING PACKAGES"

        packages=$(dpkg-query -W -f='${Package} ${version} ${Maintainer}\n' | grep "Kis SAS" | cut -d" " -f1)
        arr=($packages)
        line_number=${#arr[@]}

        if [[ $line_number == 0 || -z $line_number ]]; then
            step=99
        else
            step=$((100 / line_number))
        fi

        logThis "line number : ${line_number}, step : ${step}" "DEBUG" false

        LogAndOutputToZenity "Starting uninstalling dependencies..."

        ( (
            percent=0
            end_of_file=0
            packagesToInstall=""
            for name in "${arr[@]}"; do
                LogAndOutputToZenity "name package : ${name}" DEBUG

                if [ -z $name ]; then
                    continue
                fi

                percent=$((percent + step))
                if [ $percent -gt 99 ]; then
                    percent=99
                fi

                LogAndOutputToZenity "${percent}% : Checking $name..."
                echo "${percent}"
                packagesToInstall="${packagesToInstall} ${name}"

            done

            if [[ -n "${packagesToInstall}" ]]; then
                LogAndOutputToZenity "Uninstalling ${packagesToInstall}..."
                command="yes | sudo dpkg -r ${packagesToInstall}"
                logThis "Executing : ${command}" "DEBUG"
                (
                    eval $command
                ) |& logInfo

                command="yes | sudo dpkg --purge --force-all ${packagesToInstall}"
                logThis "Executing : ${command}" "DEBUG" false
                (
                    eval $command
                ) |& logInfo
            fi

            sudo apt-get clean 2>&1 >>$logFile
            sudo apt-get autoremove 2>&1 >>$logFile

            LogAndOutputToZenity "FINISHED"
            echo "100"

        ) |& logInfo) | zenity --width=500 --height=350 --progress \
            --title="Uninstalling services..." \
            --text="" \
            --percentage=0 \
            --auto-close

        if [[ "$?" == -1 ]]; then
            message="Uninstallation canceled"
            show_error "$message"
            DisplayEndUninstallation "N/A" "Finished - Error" "$message"
            return -1
        fi

        packages=$(dpkg-query -W -f='${Package} ${version} ${Maintainer}\n' | grep "Kis SAS" | cut -d" " -f1)
        arr=($packages)
        line_number=${#arr[@]}

        if [ $line_number != 0 ]; then
            DisplayEndUninstallation "N/A" "Finished - Success" ""
            if [[ x"${BASH_SOURCE[0]}" == x"$0" ]]; then
                exit -1
            else
                return -1
            fi
        fi

        echo "======================================================================"
        echo "REMOVING SHORTCUTS ==================================================="
        echo "======================================================================"
        RemoveShortCut

        echo "======================================================================"
        echo "REMOVING /KIS SOFT FOLDERS ==========================================="
        echo "======================================================================"
        LogAndOutputToZenity "REMOVING /KIS SOFT FOLDERS"
        DeleteKisSoftFolder

        echo "======================================================================"
        echo "END =================================================================="
        echo "======================================================================"
        LogAndOutputToZenity "END"
    ) |& logInfo) | zenity --progress --title "Uninstalling..." --pulsate --text "" --auto-close

    packageUninstalled="$?"
    # Prepare error message in case of error
    message="Uninstallation error"

else

    message="Uninstallation canceled"
    packageUninstalled=$confirmation
fi

if [ "$packageUninstalled" != 0 ]; then
    show_error "$message"
    DisplayEndUninstallation "N/A" "Finished - Error" "$message"
else
    DisplayEndUninstallation "N/A" "Finished - Success" ""
fi

#https://stackoverflow.com/a/6112629/5703228
if [[ x"${BASH_SOURCE[0]}" == x"$0" ]]; then
    exit $packageUninstalled
else
    return $packageUninstalled
fi
