#!/usr/bin/env bash

# Usage: ./generate application.sh <application-name>
# Example: ./generate application.sh hvgblog-7koznapi > .env.hvgblog-7koznapi

script_dir=$(dirname "$0")

APPLICATION_NAME=${1:-"dev"}
if [ -z "$APPLICATION_NAME" ]; then
  echo "Usage: $0 <application-name>"
  exit 1
fi

SALT_PATTERN=${SALT_PATTERN:-':alnum:!"#$%&()*+,-./:;<=>?@[\]^_`{|}~'}
SALT_LENGTH=${SALT_LENGTH:-64}

PASS_PATTERN=${PASS_PATTERN:-':alnum:'}
PASS_LENGTH=${PASS_LENGTH:-16}

APPLICATION_NAMESPACE=${APPLICATION_NAMESPACE:-'hvg-dev'}
APPLICATION_DOMAIN=${APPLICATION_DOMAIN:-'hvgblog.hu'}
APPLICATION_HOST=${APPLICATION_HOST:-"${APPLICATION_NAME}.${APPLICATION_DOMAIN}"}
APPLICATION_EMAIL=${APPLICATION_EMAIL:-'blogadmin@hvg.hu'}

CERT=${SEAL_CERT_TMP:-$(mktemp)}

if [ -z "$SEAL_CERT" ]; then
  echo "SEAL_CERT is not set, fetching..." | tee /dev/stderr
  kubeseal --fetch-cert > "$CERT"
else
  regex='(https?|ftp|file)://[-[:alnum:]\+&@#/%?=~_|!:,.;]*[-[:alnum:]\+&@#/%=~_|]'
  if [[ $SEAL_CERT =~ $regex ]]; then
    echo "SEAL_CERT looks like a URL, fetching..." | tee /dev/stderr
    curl -sSL "$SEAL_CERT" -o "$CERT"
  else
    if [ -f "$SEAL_CERT" ]; then
      echo "SEAL_CERT looks like a file path, using..." | tee /dev/stderr
      cp "$SEAL_CERT" "$CERT"
    else
      echo "SEAL_CERT is not a valid URL or file path, exiting." | tee /dev/stderr
      exit 1
    fi
  fi
fi

seal() {
  local value=$1
  echo -n "$value" |
    kubeseal --cert "$CERT" --from-file=/dev/stdin --raw --scope cluster-wide
}

gen_salt() {
  cat /dev/urandom | tr -dc "${SALT_PATTERN}" | fold -w "${SALT_LENGTH}" | head -n 1 | sed 's/\n//'
}

gen_pass() {
  cat /dev/urandom | tr -dc "${PASS_PATTERN}" | fold -w "${PASS_LENGTH}" | head -n 1 | sed 's/\n//'
}

declare -A parameters

get_parameter() {
  local key=$1
  echo "${parameters[$key]}"
}

dump_parameters() {
  echo "parameters:"
  for key in "${!parameters[@]}"; do
    echo "  - name: $key"
    echo "    value: ${parameters[$key]}"
  done
}

# shellcheck disable=SC1091
source "${script_dir}/parameters.tmp"
dump_parameters | tee
