#!/bin/bash

#$1 is a quotation-marked, space-seperated list of package names.
#$2 is the path to the program folder being installed.
#Example usage: ~/pi-apps/pkg-install "gparted buffer expect" ~/pi-apps/apps/Arduino

PKG_LIST="$1"
PRG="$(echo "$2" | tr '/' '\n' | tail -1)"

DIRECTORY="$(readlink -f "$(dirname "$0")")"

function error {
  echo -e "\e[91m$1\e[39m"
  exit 1
}

echo "Running pkg-install..."

if [ -z "$PKG_LIST" ];then
  echo -e "\e[91mNo packages were specified!\e[39m"
  exit=yes
fi

if [ -z "$PRG" ];then
  echo -e "\e[91mNo program directory specified!\e[39m"
  exitcode=1
elif [ ! -d "$2" ];then
  echo -e "\e[91m$2 does not exist!\e[39m"
  exitcode=1
elif [ -z "$(echo "$2" | grep "pi-apps/apps")" ];then
  echo -e "\e[33mWarning: That program directory ($PRG) is located outside of pi-apps.\e[39m"
fi

if [ ! -z $exitcode ];then
  echo -e '$1 is a quotation-marked, space-seperated list of package names.\n$2 is the path to the program folder being installed.\nExample usage: ~/pi-apps/pkg-install '\"'gparted buffer expect'\"' ~/pi-apps/apps/Arduino'
  echo -e "\e[91mExiting now.\e[39m"
  exit 1
fi

echo -n "Waiting until APT locks are released... "
while sudo fuser /var/lib/dpkg/lock &>/dev/null ; do
  sleep 1
done
while sudo fuser /var/lib/apt/lists/lock &>/dev/null ; do
  sleep 1
done
if [ -f /var/log/unattended-upgrades/unattended-upgrades.log ]; then
  while sudo fuser /var/log/unattended-upgrades/unattended-upgrades.log &>/dev/null ; do
    sleep 1
  done
fi
echo "Done"

DEBIAN_FRONTEND=noninteractive
LANG=C
LC_ALL=C
output="$(sudo LANG=C LC_ALL=C apt update 2>&1)"
exitcode=$?

#inform user packages are upgradeable
if [ ! -z "$(echo "$output" | grep 'packages can be upgraded' )" ];then
  echo -e "\e[33mSome packages can be upgraded.\e[39m Please consider running \e[4msudo apt full-upgrade -y\e[0m."
fi

#exit on apt error
errors="$(echo "$output" | grep '^[(W)|(E)|(Err]:')"
if [ $exitcode != 0 ] || [ ! -z "$errors" ];then
  echo -e "\e[91mFailed to run \e[4msudo apt update\e[0m\e[39m!"
  echo -e "APT reported these errors:\n\e[91m$errors\e[39m"
  exit 1
fi

#remove residual packages
sudo apt autoremove -y && sudo apt clean && sudo apt-get purge -y $(dpkg -l | grep '^rc' | awk '{print $2}')

output="$(sudo LANG=C LC_ALL=C apt-get install --no-install-recommends --dry-run $PKG_LIST 2>&1)"
echo "output: $output"

errors="$(echo "$output" | grep '^[(W)|(E)|(Err]:')"

if [ ! -z "$errors" ];then
  echo -e "\e[91mFailed to check which packages whould be installed!\e[39m"
  echo -e "APT reported these errors:\n\e[91m$errors\e[39m"
  exit 1
fi

INSTALL_LIST="$(echo "$output" | sed -n '/The following NEW packages/,/to remove/p' | sed -e '2,$!d' -e '$d' | tr -d '*' | tr '\n' ' ' | sed 's/The following.*//')"

if [ ! -z "$INSTALL_LIST" ];then
  #save that list of installed packages in the program directory for future removal
  mkdir -p "${DIRECTORY}/data/installed-packages"
  echo "$INSTALL_LIST" >> "${DIRECTORY}/data/installed-packages/${PRG}"
  
  echo -e "These packages will be installed: \e[2m$INSTALL_LIST\e[22m"
  
  #normal mode
  output="$(sudo LANG=C LC_ALL=C apt-get install -y --no-install-recommends $PKG_LIST 2>&1)"
  exitcode=$?
  echo 'Apt finished.'
  
  errors="$(echo "$output" | grep '^[(W)|(E)|(Err]:')"
  if [ $exitcode != 0 ] || [ ! -z "$errors" ];then
    echo -e "\e[91mFailed to install the packages!\e[39m"
    echo -e "APT reported these errors:\n\e[91m$errors\e[39m"
    exit 1
  fi
  #re-check package list. This time it should be blank.
  #INSTALL_LIST=''
  #for i in $PKG_LIST
  #do
  #  PKG_OK="$(dpkg-query -W --showformat='${Status}\n' "$i" 2>/dev/null | grep "install ok installed")"
  #  if [ "" == "$PKG_OK" ]; then
  #    INSTALL_LIST="${INSTALL_LIST} ${i}" #add package to install list
  #  fi
  #done
  INSTALL_LIST="$(sudo LANG=C LC_ALL=C apt-get install --no-install-recommends --dry-run $PKG_LIST | sed -n '/The following packages/,/to remove/p' | sed -e '2,$!d' -e '$d' | tr -d '*' | tr '\n' ' ' | sed 's/The following.*//')"
  
  
  if [ ! -z $INSTALL_LIST ];then
    echo -e "\e[91mAPT did not exit with an error, but these packages failed to install somehow: $INSTALL_LIST\e[39m"
    exit 1
  else
    echo -e "\e[32mAll packages were installed succesfully.\e[39m"
  fi
else
  echo -e "\e[32mNo new packages to install. Nothing to do!\e[39m"
  echo '' >> "${DIRECTORY}/data/installed-packages/${PRG}"
fi
