#!/usr/bin/env bash
#
# Run all dotfiles installers.

export current_user=house

set -e

cd "$(dirname "$0")"/..

log_section() {
  grey="\033[0;37m"
  blue="\033[0;34m"
  reset="\033[0m"

  printf '%b\n' "${grey}"
  echo
  printf '%b\n' "=== ${blue}$1${grey}"
  printf '%b\n' "==============================================================${reset}"
}

echo_time() {
  date +%s.%N
}

print_elapsed_time() {
  export LC_NUMERIC=C

  start_time="$1"
  end_time="$2"
  color_dim='\033[2m'
  color_reset='\033[0m'

  # shellcheck disable=SC2250
  elapsed_time=$(echo "scale=2; $end_time - $start_time" | bc)
  # shellcheck disable=SC2250
  formatted_time=$(printf "%.2f" "$elapsed_time")

  printf '%b' "${color_dim} -- done in ${formatted_time}s${color_reset}\n"
}

with_time() {
  export LC_NUMERIC=C

  start_time=$(echo_time)

  # Execute the command passed as arguments
  "$@"

  end_time=$(echo_time)

  # shellcheck disable=SC2250
  print_elapsed_time "$start_time" "$end_time"
}

if sudo -n true 2>/dev/null >/dev/null; then
  printf '%b\n' "\033[0;32mSudo unlocked, proceeding further\033[0m"
else
  printf '%b\n' "\033[0;31mUnlock sudo now to not be surprised by sudo prompts later\033[0m"
  sudo -v
fi

### Install pacman packages before everything
log_section script/install_pacman_packages
with_time script/install_pacman_packages
#
### Install AUR packages before everything
log_section script/install_aur_packages
with_time script/install_aur_packages

### Run special installers first, so rest can depend on them
find . -executable -name priority_install.sh | while read -r installer; do log_section "${installer}"; with_time sh -c "${installer}"; done

### Run rest of installers
find . -executable -name install.sh | while read -r installer; do log_section "${installer}"; with_time sh -c "${installer}"; done

# link everything
log_section .dotbot/install
with_time sudo .dotbot/install
echo
echo