#!/bin/bash

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

. "$scriptPath/common.sh"

displayEndInstallationDeps(){

    configuration="${1}"
    endStatus="${2}"
    endMessage="${3}"
  
    displayEnd "Installation deps" "${configuration}" "${endStatus}" "${endMessage}"
}

# Log to history log
displayEndInstallationDeps "$Group $Project $Operator $Component" "Start"

logFolder="${HOME}/installation"
logFile="${logFolder}/install-deps.log"

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

dependencies_url_file="/kis/app/dependencies.url"
dependencies_file="/kis/app/dependencies"
dependencies_file_old="/kis/app/dependencies.old"

# Get url on dependencies file
if [ ! -f $dependencies_url_file ]; then
    if [ ! -f $dependencies_file ]; then
        message="Can't find dependencies: ${dependencies_file}"
        show_error "$message"
        displayEndInstallationDeps "$Group $Project $Operator $Component" "Finished - Error" "$message"
        return 1
    fi
    message="Can't find ${dependencies_url_file}"
    show_error "$message"
    displayEndInstallationDeps "$Group $Project $Operator $Component" "Finished - Error" "$message"
    return 1
fi

# Read dependencies.url file
dependencies_url=$(cat ${dependencies_url_file})

# backup old dependencies file
if [ -f $dependencies_file ]; then
    sudo mv $dependencies_file $dependencies_file_old
fi

# Download dependencies file
LogAndOutputToZenity "Download $dependencies_url"
sudo wget -O $dependencies_file $dependencies_url -q -o $logFile

if [ $? -ne 0 ] ; then
    LogAndOutputToZenity "Can't download dependencies: ${dependencies_url}"
    if [ ! -f $dependencies_file_old ]; then
        message="Can't find dependencies: ${dependencies_file}"
        show_error "$message"
        displayEndInstallationDeps "$Group $Project $Operator $Component" "Finished - Error" "$message"
        return 1
    else
        # Restore old dependencies file
        sudo mv $dependencies_file_old $dependencies_file
    fi
fi

sudo rm -f $dependencies_file_old

# update package list
sudo apt-get update 2>&1 >> $logFile
# Install all service packages with the correct version

line_number=$(wc -l $dependencies_file | awk '{ print $1 }')

step=$((100 / line_number))
logThis "line number : ${line_number}, step : ${step}" "DEBUG" false

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

LogAndOutputToZenity "Start installing dependencies..."

errorTmp=`mktemp`

( (
percent=0
end_of_file=0
dependencies_file="/kis/app/dependencies"
fileNamesArray=()
packagesToInstall=""

maxDownloadTry=10
currentTry=0
waitingTime=60
fileControl=false

#Read File /kis/app/dependencies line by line
while [[ $end_of_file == 0 ]]; do
  read -r package
#   the last exit status is the 
#   flag of the end of file
  end_of_file=$?

  #Extract Package name and version
  name=$(echo "$package" | cut -d"=" -f1)
  version=$(echo "$package" | cut -d"=" -f2)

  if [ -z $name ]; then
    continue
  fi

  percent=$((percent+step))
  if [ $percent -gt 99 ]; then
    percent=99
  fi
  LogAndOutputToZenity "${percent}% : Checking $package..."
  echo "${percent}"

  #Add current package name to package list 
  packagesToInstall="${packagesToInstall} ${name}=${version}"
  #add package name to package Array (to check later if file exist)
  fileNamesArray+=( "${name}_${version}*.deb" )

done < "$dependencies_file"

LogAndOutputToZenity "Downloading packages..."

while [[ "$fileControl" == false && $currentTry -lt $maxDownloadTry ]]; do
  LogAndOutputToZenity "Trying to download files : $currentTry / $maxDownloadTry "
  DownloadAndCheckPackages
  (( currentTry++ ))
done

if [[ "$fileControl" == false ]]; then
  message="Failed to download packages check internet connexion and try again"
  printf '%s\n' "${message}" > "$errorTmp"

else

  allDebsFiles=$(ls *.deb)
  logThis "File downloaded : $allDebsFiles" "DEBUG" false

  LogAndOutputToZenity "All packages downloaded"
  LogAndOutputToZenity "Installing packages..."
  sudo dpkg -i $allDebsFiles | grep "^[^#;]"

  message="Success"

fi

LogAndOutputToZenity "Cleaning debian packages..."
sudo rm *.deb

LogAndOutputToZenity "FINISHED with result : $message"
echo "100"

) |& logInfo ) | 
zenity --width=500 --height=350 --progress \
  --title="Installing services..." \
  --text="" \
  --pulsate

result=$?

# Clean space
sudo apt-get autoclean -y 2>&1 >> $logFile
sudo apt-get autoremove -y 2>&1 >> $logFile

if [[ $result == 1 || -s $errorTmp ]] ; then

    if [[ "$result" == 1 ]]; then
      message="Installation canceled"
    else
      value=`cat $errorTmp`
      message="Error while installing packages : $value"
    fi

    show_error "$message"
    displayEndInstallationDeps "$Group $Project $Operator $Component" "Finished - Error" "$message"
    return 1
fi

# Update installed packages file
sudo rm /kis/installed-packages
dpkg-query -W -f='${Package} ${version} ${Maintainer}\n' | grep "Kis SAS" > /kis/installed-packages

LogAndOutputToZenity "Dependencies installation done"

displayEndInstallationDeps "$Group $Project $Operator $Component" "Finished - Success"