#!/bin/bash
# common.sh
#       Functionality:
#           helper script that simplifies the call
#           of recurrent methods in the installation and removal scripts of the application
#       Used by :
#           -uninstall.sh
#       Dependencies :
#           - logger.sh

#____________________________________________ INCLUDE ____________________________________________
# Include scripts
scriptPath=$(dirname "${BASH_SOURCE[0]}")
. "$scriptPath/logger.sh"

logFolder="${HOME}"
logFile="${logFolder}/installation_history.log"

sudo touch "$logFile"
sudo chmod a+rw "$logFile"

purgeLogs

#____________________________________________ FUNCTIONS ____________________________________________

#######################################
# print_title_1
# Globals:
#   None
# Arguments:
#   string $1
#######################################
print_title_1() {
    echo -e "\e[104m====> $1                                                                                                    \e[0m"
}

#######################################
# print_title_2
# Globals:
#   None
# Arguments:
#   $1
#######################################
print_title_2() {
    echo -e "\e[35m   => $1\e[0m"
}

#######################################
# print_title_3
# Globals:
#   None
# Arguments:
#   $1
#######################################
print_title_3() {
    echo -e "\e[33m     => $1\e[0m"
}

#######################################
# print_result
# Globals:
#   None
# Arguments:
#   $1 $2
#######################################
print_result() {
    if [ $1 -eq 0 ]; then
        echo -e "\e[32m  $2 => Success \e[0m"
    else
        echo -e "\e[31m  $2 => Error \e[0m" >&2
    fi
}

#######################################
# check_internet
# Globals:
#   None
# Arguments:
#   $1 the url
# Outputs:
#   bool : true or false
#######################################
check_internet() {
    if [[ -z $1 ]]; then
        url="https://debs.photo-me.eu"
    else
        url=$1
    fi
    wget -q --spider $url

    result=$?

    return $result
}

#######################################
# LogAndOutputToZenity
# Globals:
#   logThis -> function logger.sh
# Arguments:
#   $1 Message
#   $2 Priority (INFO, DEBUG)
#######################################
LogAndOutputToZenity() {
    if [[ -z "${2}" ]]; then
        priority="INFO"
    else
        priority=${2}
    fi

    echo "# $1"
    logThis "$1" "${priority}" false
}

#######################################
# LogAndOutputToZenity
# Globals:
#
# Arguments:
#
# Ouputs:
#
#######################################
DownloadAndCheckPackages() {
    LogAndOutputToZenity "# Downloading packages ${packagesToInstallArray[@]}"
      
    # CV3STA-209
    sudo apt clean -qq >/dev/null 2>&1
    sudo apt-get autoremove -qq >/dev/null 2>&1

    sudo apt-get download ${packagesToInstall} 2>&1 >>$logFile

    fileControl=true

    for t in ${fileNamesArray[@]}; do
        LogAndOutputToZenity "Looking for file $t"
        if [ $(ls $t 2>/dev/null | wc -l) -gt 0 ]; then
            LogAndOutputToZenity "Matching file found"
        else
            LogAndOutputToZenity "File not found, retry download in $waitingTime secondes ($currentTry / $maxDownloadTry)"
            fileControl=false
        fi
    done
    if [ "$fileControl" = false ]; then
        sleep $waitingTime
    fi
}

#######################################
# show_error
# Globals:
#
# Arguments:
#
# Ouputs:
#
#######################################
show_error() {
    logThis "${1}" "ERROR" false
    zenity --error --text="${1}" --width=500 --height=350
}

#######################################
# displayEnd
# Globals:
#
# Arguments:
#
# Ouputs:
#
#######################################
displayEnd() {
    step="${1}"
    configuration="${2}"
    status="${3}"
    endMessage="${4}"

    backupLogFolder="${logFolder}"
    backupLogFile="${logFile}"

    logFolder="${HOME}"
    logFile="${logFolder}/installation_history.log"

    logThis "${step} ${configuration} - ${endStatus} ${endMessage}" "INFO"

    logFolder="${backupLogFolder}"
    logFile="${backupLogFile}"
}

#######################################
# DisplayEndUninstallation
# Globals:
#   $1 configuration message
#   $2 status message
#   $3 end message (optional)
# Arguments:
#   None
# Outputs:
#   None
#######################################
DisplayEndUninstallation() {
    configuration="${1}"
    endStatus="${2}"
    endMessage="${3}"
    displayEnd "Uninstallation" "${configuration}" "${endStatus}" "${endMessage}"
}

#######################################
# MenuLog
# Globals:
#   Args
# Arguments:
#   None
# Outputs:
#   None
#######################################
MenuLog() {
    POSITIONAL=()
    while [[ $# -gt 0 ]]; do
        key="$1"

        case $key in
        -v | --verbose)
            scriptLoggingLevel="DEBUG"
            shift # past argument
            ;;
        -h | --help)
            help="-v | --verbose : more log \n\ -h | --help : display this help"
            echo -e $help
            exit 0
            shift # past argument
            ;;
        *)                     # unknown option
            POSITIONAL+=("$1") # save it in an array for later
            shift              # past argument
            ;;
        esac
    done
    set -- "${POSITIONAL[@]}" # restore positional parameters
}

#######################################
# ConfirmUninstall
# Globals:
#   Args
# Arguments:
#   None
# Outputs:
#   None
#######################################
ConfirmUninstall() {
    # Confirm user if he wants to unistall
    zenity --question --width=500 --height=350 \
        --title "Are you sure" \
        --text "Are you sure you want to unistall all kis packages ? (statistics and counters will be saved in /kis/backup)"

    result=$?

    if [ $result != 0 ]; then
        DisplayEndUninstallation "N/A" "Error" "Canceled"
    fi

    return $result
}

#######################################
# GetKisPackage
# Globals:
#   Args
# Arguments:
#   None
# Outputs:
#   Array of name packages kis
#######################################
GetKisPackage() {
    packages=$(dpkg-query -W -f='${Package} ${version} ${Maintainer}\n' | grep "Kis SAS" | cut -d" " -f1)
    arr=($packages)
    return $arr
}

#######################################
# RemoveShortCut
# Globals:
#   Args $HOME
# Arguments:
#   None
# Outputs:
#   None
#######################################
RemoveShortCut() {
    LogAndOutputToZenity "REMOVING SHORTCUTS"

    rm -f ${HOME}/Desktop/kis-launcher.desktop
    rm -f ${HOME}/Desktop/kis-supervisor.desktop

    rm -f ${HOME}/Desktop/verifone-configurator.desktop
    rm -f ${HOME}/Desktop/payment-tool.desktop
    rm -f ${HOME}/Desktop/castle-configurator.desktop

    rm -f ${HOME}/.config/autostart/kis-start.desktop

    rm -f ${HOME}/Desktop/hardwareApp.desktop

    rm -f ${HOME}/Desktop/maintenance-configurator.desktop

    rm -f ${HOME}/Desktop/ticketZ.desktop

    rm -f ${HOME}/Desktop/rileva-configuration.desktop
}

#######################################
# Backup counter and statistics
# Globals:
#   Args
# Arguments:
#   None
# Outputs:
#   None
#######################################
Backup() {
    sudo mkdir /kis/backup
    sudo cp /kis/static/statistics/* /kis/backup/
    sudo cp /kis/static/configuration/services/payment/counter.txt /kis/backup/counter.txt
}

#######################################
# DeleteKisSoftFolder
# Globals:
#   Args
# Arguments:
#   None
# Outputs:
#   None
#######################################
DeleteKisSoftFolder() {
    sudo rm -rf /kis/app
    sudo rm -rf /kis/configuration
    sudo rm -rf /kis/static
    sudo rm -rf /kis/data
}
