#!/usr/bin/env bash

# Please Use Google Shell Style: https://google.github.io/styleguide/shell.xml

# ---- Start unofficial bash strict mode boilerplate
# http://redsymbol.net/articles/unofficial-bash-strict-mode/
set -o errexit  # always exit on error
set -o errtrace # trap errors in functions as well
set -o pipefail # don't ignore exit codes when piping output
set -o posix    # more strict failures in subshells
# set -x          # enable debugging

IFS="$(printf "\n\t")"
# ---- End unofficial bash strict mode boilerplate

cd "$(dirname "${BASH_SOURCE[0]}")/.."
env_file=./.env

function main() {
  set -e

  add_new_env_vars
}

function file_ends_with_newline() {
  [[ $(tail -c1 "${env_file}" | wc -l) -gt 0 ]]
}

function add_new_env_vars() {
  # create .env and set perms if it does not exist
  [[ ! -f "${env_file}" ]] && {
    touch "${env_file}"
    chmod 0600 "${env_file}"
  }

  # if the file does not end with new line add a new line to it
  if ! file_ends_with_newline; then
    echo "" >> "${env_file}"
  fi

  find . -name .env.example -type f -print0 |
    (xargs -0 grep -Ehv '^\s*#' || true) |
    sort |
    {
      while IFS= read -r var; do
        if [[ -z "${var}" ]]; then
          continue
        fi
        key="${var%%=*}" # get var key
        # only eval for dynamic vars if the value has a dollar sign
        if [[ "${var}" =~ "$" ]]; then
          var="$(eval echo "${var}")" # generate dynamic values
        fi
        # If .env doesn't contain this env key, add it
        if ! grep -qLE "^${key}=" "${env_file}"; then
          echo "Adding $key to .env"
          echo "$var" >>"${env_file}"
        fi
      done
    }
}

main
