#!/usr/bin/env bash

set -eo pipefail

# ------------------------------ Helper Functions ------------------------------

## Indent input text by "indents" indentations where 1 indentation is 2 spaces 
#
# Usage:
#   $ echo "SAMPLE_TEXT" | indent 2
#       SAMPLE_TEXT

indent() {
  local indents=$1; indents=${indents:-1}
  pr -to $((indents * 2))
}

## Validates if input is a valid Imply environment variable
#
# Usage:
#   $ is_valid_imply_var imply_defaults_myDefault
#   $ echo $?
#   $ 0

is_valid_imply_var() {
  echo "$1" |
    grep -E '^IMPLY_|^imply_|^implyfe_' |
    grep -q '^[_[:alpha:]][_[:alpha:][:digit:]]*$' &&
    return ||
    return 1
}

## Load file name and contents as environment variables
#
# Format : {filename}={fileContents}
#
# Here the filename is the environment variable name to be set and the file
# contents is the value the environment variable will be set to

load_file_as_env() {
  for FILEPATH in "$@"; do
    VAR_DIR="$(dirname "${FILEPATH}")"
    VAR_NAME="$(basename "${FILEPATH}")"

    if is_valid_imply_var "${VAR_NAME}"; then
      printf -v "${VAR_NAME}" %s "$(cat "${FILEPATH}")"
      echo "Set var [${VAR_NAME}] from [${VAR_DIR}]"
    else
      echo "Ignoring [${VAR_NAME}] from [${VAR_DIR}]"
    fi
  done
}

## Check if environment variable/s are set
#
# Usage:
#   FOO="BAR"
#   $ assert_var_set FOO
#
#   $ assert_var_set BAR
#   BAR must be provided as an environment variable

assert_var_set() {
  for VAR in "$@"; do
    if [ -z "${!VAR}" ]; then
      echo "${VAR} must be provided as an environment variable"
      return 1
    fi
  done
}
