#!/bin/bash
#
# Linux CLI Uninstaller
#
# Copyright 2015-2021 ARM Limited. All rights reserved.

set -eu -o pipefail

packages="armpl-21.0-gcc-10.2 arm-performance-libraries-21.0-gcc-10.2"

removal_command="rpm -e"
function in_use () { rpm --query --quiet --whatrequires $1; }

if [[ ${removal_command} == "dpkg -r" ]]; then
  dpkg_packages=""
  for package in $packages; do
    p="$(echo  "${package//_/-}" | tr '[:upper:]' '[:lower:]')"
    dpkg_packages="$dpkg_packages $p"
  done
  packages="$dpkg_packages"
fi

declare -r THIS_DIRECTORY=$( cd "$(dirname "${BASH_SOURCE[0]}")" > /dev/null 2>&1; pwd  -P)
declare -r INSTALLED_FILE_LIST="${THIS_DIRECTORY}/.installed_files"

if [[ ! -r $INSTALLED_FILE_LIST ]]; then
  if [[ $EUID -ne 0 ]]; then
    echo "You do not appear to be running as a privileged user."
    echo "Going ahead with the uninstall anyway..."
  fi
  to_process=$packages
  removed_one=1
  while [[ -n "$to_process" && $removed_one -eq 1 ]]; do
    packages="$to_process"
    to_process=""
    removed_one=0
    for package in $packages; do
      if [[ $package =~ ^gcc  && $packages == " $package" ]]; then
        if in_use "$package"; then
          echo "In use by other packages: $package"
          break
        fi
      fi
      if $removal_command "$package"  > /dev/null 2>&1; then
        removed_one=1
        echo "Uninstalled $package"
      else
        to_process="$to_process $package"
      fi
    done
  done
  if [[ -n "$to_process" ]]; then
    echo "Unable to uninstall the following packages:"
    for package in $to_process; do
      echo "  $package";
    done
    # Show the user why things failed to uninstall
    $removal_command $to_process
  fi
else
  # Uninstall by removing everything in INSTALLED_FILE_LIST
  suite_dir=$(basename "${THIS_DIRECTORY}")
  echo "Removing installed files..."
  for item in $(sort -r "$INSTALLED_FILE_LIST"); do
    if [[  $item =~ ^${suite_dir}$ ]]; then
      continue
    fi
    item="${THIS_DIRECTORY}/../${item}"
    if [[ -f $item || -h $item ]]; then
      rm "$item"
    elif [[ -d $item ]]; then
      if [[ -z $(ls -A "$item") ]]; then
        rmdir "$item"
      else
        echo "warning: non-empty directory $item"
      fi
    else
      if [[ -e $item ]]; then
        echo "warning: unrecognized file type for $item"
      else
        echo "warning: file already removed $item"
      fi
    fi
  done
  rm "$INSTALLED_FILE_LIST"
  rmdir "$THIS_DIRECTORY"
fi