#!/bin/bash

# Include scripts
scriptPath=$(dirname "${BASH_SOURCE[0]}")

. "$scriptPath/common.sh"

# Install last certificates versions
sudo apt install -qq -d ca-certificates

# First check internet connection
echo "# Checking internet connexion"
check_internet >/dev/null 2>&1
internet=$?

if [ ${internet} != 0 ]; then
    show_error "$internet Internet connection failed"
    exit 1
fi

# Unistall first
./uninstall.sh

if [ $? != 0 ]; then
    exit 1
fi

echo "# Getting arguments"
# the script arguments can be used to override following dialogboxes
# If no argument then we will display the dialogboxes to set those parameters
POSITIONAL=()
while [[ $# -gt 0 ]]
do
key="$1"

case $key in
    -r|--repository)
    Repository="$2"
    shift # past argument
    shift # past value
    ;;
    -o|--operator)
    Operator="$2"
    shift # past argument
    shift # past value
    ;;
    -c|--component)
    Component="$2"
    shift # past argument
    shift # past value
    ;;
    -m|--machineName)
    MachineName="$2"
    shift
    shift
    ;;    
    *)    # unknown option
    POSITIONAL+=("$1") # save it in an array for later
    shift # past argument
    ;;
esac
done
set -- "${POSITIONAL[@]}" # restore positional parameters

if [[ -z $Group ]]; then

    # Gather all groups
    i=0
    groupsArg=""
    while read -r line
    do
        prefix="FALSE "
        if [[ $i == 0 ]]; then
            prefix="TRUE "
        fi
        
        groupsArg="${groupsArg}${prefix}${line} "
        i+=1
    done < <(curl -s https://debs.photo-me.eu/installation/dependencies/ | grep -Po "(?<=>)(\w*-*\w*)(?=\/<)")

    Group=$(zenity --list --width=500 --height=350 --radiolist --title "Select group" --text="Available groups:" --column="" --column="Group" ${groupsArg})
    if [[ -z $Group ]]; then
        show_error "# No group chosen"
        exit 1
    fi
fi

if [[ -z $Operator ]]; then
    # Gather all operators
    i=0
    operatorsArg=""
    while read -r line
    do
        prefix="FALSE "
        if [[ $i == 0 ]]; then
            prefix="TRUE "
        fi
        
        operatorsArg="${operatorsArg}${prefix}${line} "
        i+=1
    done < <(curl -s https://debs.photo-me.eu/installation/dependencies/${Group}/laundry/revolution/ | grep -Po "(?<=>)(\w*-*\w*)(?=\/<)")

    Operator=$(zenity --list --width=500 --height=350 --radiolist --title "Select operator" --text="Available operators:" --column="" --column="Operator" ${operatorsArg})
    if [[ -z $Operator ]]; then
        show_error "# No operator chosen"
        exit 1
    fi
fi

dep_rul="https://debs.photo-me.eu/installation/dependencies/${Group}/laundry/revolution/${Operator}/"
echo "dependencies file at ${dep_rul}"

if [[ -z $Component ]]; then

    # Gather all components
    i=0
    componentsArg=""
    while read -r line
    do
        prefix="FALSE "
        if [[ $i == 0 ]]; then
            prefix="TRUE "
        fi
        
        componentsArg="${componentsArg}${prefix}${line} "
        i+=1
    done < <(curl -s ${dep_rul} | grep -Po "(?<=>)(\w*-*\w*)(?=\/<)")

    Component=$(zenity --list --width=500 --height=350 --radiolist --title "Select component" --text="Available components:" --column="" --column="Component" ${componentsArg})
    if [[ -z $Component ]]; then
        show_error "# No component chosen"
        exit 1
    fi
fi

MachineName=$(zenity --entry --title "Machine name" --text "Please enter machine name:")
if [[ -z $MachineName ]]; then
    show_error "# No machine name"
    exit 1
fi


if [[ -z $Repository ]]; then
    Repository="${Operator}-${Component}"
fi

echo "# Start installation from following repository:"

echo "# Adding Apt source to:"
echo "# Repository = ${Repository}"
echo "# Operator = ${Operator}"
echo "# Component = ${Component}"

if [[ -n /etc/apt/trusted.gpg.d/kis-aptly.gpg ]] ; then
    echo "# Adding aptly key..."
    curl https://debs.photo-me.eu/aptly_repo_signing.key | sudo apt-key --keyring /etc/apt/trusted.gpg.d/kis-aptly.gpg add 
fi

echo "# Creating /etc/apt/sources.list.d/kis-app.list..."

aptsource="/etc/apt/sources.list.d/kis-app.list"

if [[ -f ${aptsource} ]] ; then
    echo "# Deleting ${aptsource}"
    sudo rm -f ${aptsource}
fi

if [[ -n ${aptsource} ]] ; then
    echo "# Creating ${aptsource}"
    echo "deb [arch=armhf] https://debs.photo-me.eu/${Repository} ${Operator} ${Component}" > ./kis-app.list
    sudo cp ./kis-app.list ${aptsource}
    rm ./kis-app.list
fi

echo "# Download dependencies file..."

dependencies_url="https://debs.photo-me.eu/installation/dependencies/${Group}/laundry/revolution/${Operator}/${Component}/aptly_dependencies"

sudo mkdir -p /kis/app

# Delete dependencies.old backup because a new one has been downloaded
sudo rm -f /kis/app/dependencies
sudo rm -f /kis/app/dependencies.url

echo "# Writing /kis/app/dependencies.url with ${dependencies_url}"
echo "${dependencies_url}" | sudo tee -a /kis/app/dependencies.url

echo "# Apt update"

sudo apt update >/dev/null 2>&1

echo "# Installing all packages from dependencies url"

sudo ./install-dependencies.sh

echo "# Changing machine name to ${MachineName}..."

sudo apt install -y jq >/dev/null 2>&1

echo "$(jq --arg MachineName "$MachineName" '.MachineName = $MachineName' /kis/static/configuration/global.json)" > /kis/static/configuration/global.json

echo "# Restoring backed up stats (if any)"

backupFolder="/kis/backup"

if [[ -d $backupFolder ]]; then
    sudo mv -n ${backupFolder}/*.json /kis/static/statistics/
    sudo mv -n ${backupFolder}/counter.txt /kis/static/configuration/services/payment/counter.txt
fi

# We need to create them here as dpkg packages should not create anything in user folders at install (see Debian guidelines)
echo "# Creating desktop shortcuts"

ln -s /kis/app/services/receipt/ticketZ.desktop ${HOME}/Desktop/ticketZ.desktop

ln -s /kis/app/services/payment/payment-tool.desktop ${HOME}/Desktop/payment-tool.desktop
ln -s /kis/app/services/payment/verifone-configurator.desktop ${HOME}/Desktop/verifone-configurator.desktop
ln -s /kis/app/services/payment/castle-configurator.desktop ${HOME}/Desktop/castle-configurator.desktop

ln -s /kis/app/services/hardware/hardwareApp.desktop ${HOME}/Desktop/hardwareApp.desktop

ln -s /kis/app/services/maintenance-configurator/maintenance-configurator.desktop ${HOME}/Desktop/maintenance-configurator.desktop

ln -s /kis/app/launcher/kis-launcher.desktop ${HOME}/Desktop/kis-launcher.desktop
ln -s /kis/app/supervisor/kis-supervisor.desktop ${HOME}/Desktop/kis-supervisor.desktop

echo "# Configuring TeamViewer log level"

tvConfPath="/etc/teamviewer/global.conf"
# Escape brackets opening for grep
logLevelVar="\[int32] Log_Level"
logLevelValue="200"
logLevel="${logLevelVar} = $logLevelValue"
isLogLevelSet=$(sudo cat "$tvConfPath" | grep "${logLevelVar}")

if [[ -z $isLogLevelSet ]];then
    echo "${logLevel}" | sudo tee -a "${tvConfPath}"
    echo "TeamViewer log level set to $logLevelValue"
fi

echo "# Deleting installation files"
sudo rm -rf /kis/app/docker

echo "# Installation finished"