#!/bin/bash

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

. "$scriptPath/common.sh"

logFolder="/kis/app"
logFile="${logFolder}/install-deps.log"

touch $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
        show_error "Can't find dependencies: ${dependencies_file}"
        exit 1
    fi
    show_error "Can't find ${dependencies_url_file}"
    exit 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
echo "# Download $dependencies_url"
sudo wget -O $dependencies_file $dependencies_url >/dev/null 2>&1

if [ $? -ne 0 ] ; then
    print_result 1 "Can't download dependencies: ${dependencies_url}"
    if [ ! -f $dependencies_file_old ]; then
        show_error "Can't find dependencies: ${dependencies_file}"
        exit 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 update > $logFile
# Install all service packages with the correct version

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

step=$((100 / line_number))
echo "line number : ${line_number}, step : ${step}"

print_title_2 "Stabilizing dpkg..."
# Make sure dpkg is in a valid state
sudo dpkg --configure -a
sudo apt clean

echo "# Start installing dependencies..."

( (
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
  echo "# ${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"

echo "# Downloading packages..."

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

if [[ "$fileControl" == false ]]; then
  show_error "Failed to download packages check internet connexion and try again"
  exit 1
fi

allDebsFiles=$(ls *.deb)
echo $allDebsFiles

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


echo "Cleaning debian packages"
sudo rm *.deb

echo "# FINISHED"
echo "100"

) | tee $logFile ) | 
zenity --width=500 --height=350 --progress \
  --title="Installing services..." \
  --text="" \
  --pulsate

if [ "$?" = -1 ] ; then
    show_error "Installation canceled."
fi

# Clean space
sudo apt-get autoclean -y >/dev/null 2>&1
sudo apt-get autoremove -y >/dev/null 2>&1

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

echo "# Dependencies installation done"