#!/usr/bin/env bash
# vim: ft=sh
# —————————————————————————————————————————————————————————————————————————————————————
# NOTE: These setup scripts rely on an open source BASH framework BashMatic.
#       https://github.com/kigster/bashmatic
#
# The framework is pretty light-weight, and is installed in your $HOME/.bashmatic folder.
# You can safely remove that folder after the setup if you wish, although re-running the
# setup will re-install it.
# —————————————————————————————————————————————————————————————————————————————————————


export BASHMATIC_OS="$(uname -s | tr '[:upper:]' '[:lower:]')"
[[ -z ${BASHMATIC_HOME} ]] && export BASHMATIC_HOME="${HOME}/.bashmatic"
[[ -d ${BASHMATIC_HOME} ]] || bash -c "$(curl -fsSL https://raw.githubusercontent.com/kigster/bashmatic/master/bin/bashmatic-install); bashmatic-install -v -f -b v2.7.2"

# shellcheck disable=SC1090
source "${BASHMATIC_HOME}/init.sh" 1>/dev/null 2>&1
command -v rbenv >/dev/null && eval "$(rbenv init -)"

__version.detect() {
  local file="$1"
  if [[ -f ${file} ]]; then
    /bin/cat "${file}" | head -1
  else
    printf ''
  fi
}

[[ -f .bazelversion ]] || {
  error "Can't find .bazelversion file, required for installing Bazel!"
  exit 1
}

# Application Constants
export RulesRuby__RulesVersion="$(__version.detect .rules_version)"
export RulesRuby__RubyVersion="$(__version.detect .ruby-version)"
export RulesRuby__BazelVersion="$(__version.detect .bazelversion)"

bazel-sha() {
  bazel info | grep output_path | awk 'BEGIN{FS="/"}{ for(i = 1; i <= NF; i++) { if (length($i) == 32) print $i; } }'
}

help-header() {
  printf "${bldylw}$*${clr}"
}

help-usage() {
  printf "  ${bldgrn}$*${clr}"
}

help-example() {
  printf "    ${bldpur}$*${clr}"
}

deps.start-clock() {
  export __start=$(millis)
}

deps.print-duration() {
  local finish=$(millis)
  local duration=$((finish - __start))
  info "Total running time for was ${bldylw}$(time.duration.millis-to-secs ${duration}) seconds.\n\n"
}

run.set-all abort-on-error

# ensure we can exit with Ctrl-C
trap exit 1 INT
