#!/bin/bash

# Save this file as ~/.config/yadm/bootstrap and make it executable. It will
# execute all executable files (excluding templates and editor backups) in the
# ~/.config/yadm/bootstrap.d directory when run.

_repeat() {
  local start=1
  local end=${1:-80}
  local str="${2:-=}"
  local range=$(seq $start $end)
  for i in $range; do echo -n "${str}"; done
}

_header() {
  local length="$1"
  echo -n "/="
  _repeat ${length} "="
  echo "=\\"
}
_value() {
  local value="$1"
  echo -n "| "
  echo -n ${value}
  echo " |"
}
_footer() {
  local length="$1"
  echo -n "\\="
  _repeat ${length} "="
  echo "=/"
}

display() {
  local value="$1"
  _header ${#value}
  _value "${value}"
  _footer ${#value}
}

runfile() {
  local command="$1"
  local prompt="Do you wish to run $command? [Ynq]"
  local display="Executing $command"

  local promptLength=$((${#prompt}))
  local displayLength=${#display}

  local maxWidth=$((promptLength > displayLength ? promptLength : displayLength))

  _header ${maxWidth}

  read -p "| $prompt |" -n 1 -r -s
  echo

  if [[ $REPLY =~ ^[Nn]$ ]]; then
    _footer ${maxWidth}
    return
  fi

  if [[ $REPLY =~ ^[Qq]$ ]]; then
    _footer ${maxWidth}
    display "Exiting..."
    exit 0
  fi

  echo -n "| $display"
  _repeat $((maxWidth - displayLength)) " "
  echo " |"

  _footer ${maxWidth}

  if ! "$command"; then
    echo "Error: bootstrap '$command' failed" >&2
    exit 1
  fi
}

set -eu

SCRIPTPATH="$(
  cd -- "$(dirname "$0")" >/dev/null 2>&1
  pwd -P
)"
# Directory to look for bootstrap executables in
BOOTSTRAP_D="$SCRIPTPATH/bootstrap.d"

$SCRIPTPATH/_set_class.sh

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

declare -a bootstraps
while IFS= read -r bootstrap; do
  if [[ -x "$bootstrap" && ! "$bootstrap" =~ "##" && ! "$bootstrap" =~ ~$ && ! "$bootstrap" =~ ".bak" ]]; then
    bootstraps+=("$bootstrap")
  fi
done < <(find -L "$BOOTSTRAP_D" -type f | sort)

for bootstrap in "${bootstraps[@]}"; do
  runfile "$bootstrap"
done

"$SCRIPTPATH/apply_changes"

display "Bootstrap completed"
