#!/bin/bash

#$1 is the path to the program folder being installed. For example, /home/pi/pi-apps/apps/Arduino
#Example usage: ~/pi-apps/uninstall-installed ~/pi-apps/apps/Arduino

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

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

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

if [ ! -z $exitcode ];then
  echo -e "\e[91mExiting now.\e[39m"
  exit 1
fi

function error {
  echo -e "\e[91m$1\e[39m"
  exit 1
}
echo "Running purge-installed..."
PKG_LIST="$(cat "${DIRECTORY}/data/installed-packages/${PRG}")"

if [ ! -f "${DIRECTORY}/data/installed-packages/${PRG}" ];then
  echo -e "\e[33mDoes ${DIRECTORY}/data/installed-packages/${PRG} exist?\e[39m"
  exit 0
fi

if [ -z "${DIRECTORY}/data/installed-packages/${PRG}" ];then
  echo "Nothing to purge. Exiting now."
  exit 0
fi

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

PURGE_LIST="$(sudo LANG=C apt-get purge --dry-run $PKG_LIST | sed -n '/The following packages will be REMOVED/,/to remove and/p' | sed -e '2,$!d' -e '$d' | tr -d '*' | tr '\n' ' ' | sed 's/The following.*//')"
echo "These packages will be purged: $PURGE_LIST"

#normal mode
output="$(sudo LANG=C apt purge -y $PKG_LIST 2>&1)"
exitcode=$?

errors="$(echo "$output" | grep '^[(W)|(E)|(Err]:')"
if [ $exitcode != 0 ] || [ ! -z "$errors" ];then
  echo -e "\e[91mFailed to uninstall the packages!\e[39m"
  echo -e "APT reported these errors:\n\e[91m$errors\e[39m"
  exit 1
fi

#ensure all packages are really purged
PURGE_LIST="$(sudo LANG=C apt-get purge --dry-run $PKG_LIST | sed -n '/The following packages/,/to remove/p' | sed -e '2,$!d' -e '$d' | tr -d '*' | tr '\n' ' ')"

if [ ! -z "$PURGE_LIST" ];then
  error "APT did not exit with an error, but these packages are still installed somehow: $PURGE_LIST"
else
  echo -e "\e[32mAll packages were purged succesfully.\e[39m"
  gio trash "${DIRECTORY}/data/installed-packages/${PRG}"
fi