#!/bin/env sh

set -eu

SCRIPTPATH="$(
  cd -- "$(dirname "$0")" >/dev/null 2>&1
  pwd -P
)"
APPLICATIONS_PATH="$SCRIPTPATH/applications"

$SCRIPTPATH/functions/set_class.sh
source $SCRIPTPATH/functions/pkg.sh

if [[ ! -d "$APPLICATIONS_PATH" ]]; then
  echo "Error: applications directory '$APPLICATIONS_PATH' not found" >&2
  exit 1
fi

echo -n "# Updating system"
updateSystem

echo "# Gathering applications"

declare -x -a applications
declare -x -a actions
actions=()
declare -x -a gitInstalls

applications+=("")

addApplications ()
{
  for application in "$@"; do
    applications+=("$application")
  done
}

addActions() 
{
  for action in "$@"; do
    actions+=("$action")
  done
}

addGitInstall() {
  local name=$1
  local path=$2
  local setupCommand=$3

  gitInstalls+=("$name;$path;$setupCommand")
}

while IFS= read -r file; do
  if [[ -x "$file" && ! "$file" =~ "##" && ! "$file" =~ ~$ && ! "$file" =~ ".bak" ]]; then
    source $file
  fi
done < <(find -L "$APPLICATIONS_PATH" -type f | sort) 


echo -n "# Installing/Updating applications (${#applications[@]})"
installPackages ${applications[*]}

checkGitInstallExistance() {
  local path=$1

  if [ ! -d $path ]; then
    return 0
  fi

  PREV_DIRECTORY=$PWD

  cd $path

  if ! git remote update && git status | grep behind >>/dev/null; then
    cd $PREV_DIRECTORY
    return 0
  fi

  return 1
}

runGitInstall() {
  local targetPath=$1
  local repository=$2
  local setupCommand=$3

  PREV_DIRECTORY=$PWD

  if [ ! -d "$targetPath" ]; then
    git clone "$repository" "$targetPath"
  fi

  cd $targetPath

  $setupCommand

  cd $PREV_DIRECTORY
}

for gitInstall in "${gitInstalls[@]}"
do
  arrIN=(${gitInstall//;/ })
  targetPath="$HOME/.cache/${arrIN[0]}"

  echo "Installing... ${arrIN[0]}"
  runGitInstall "$targetPath" "${arrIN[1]}" "${arrIN[2]}"
done

echo "# Executing actions... (${#actions[@]})"
for action in "${actions[@]}";
do
  echo "==> Now executing: ${action}"
  $action
done
