#!/usr/bin/env bash
set -euo pipefail

project_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
env_file="${1:-$project_dir/.env}"
template_file="$project_dir/.env.example"

if [[ ! -f "$template_file" ]]; then
  echo "Missing template: $template_file" >&2
  exit 1
fi

umask 077

if [[ ! -e "$env_file" ]]; then
  cp "$template_file" "$env_file"
elif [[ ! -f "$env_file" || -L "$env_file" ]]; then
  echo "Refusing to modify a non-regular file or symlink: $env_file" >&2
  exit 1
fi

set_if_empty() {
  local key="$1"
  local value="$2"
  local temporary

  if grep -Eq "^${key}=.+$" "$env_file"; then
    return
  fi

  temporary="$(mktemp "${env_file}.XXXXXX")"
  awk -v key="$key" -v value="$value" '
    BEGIN { found = 0 }
    $0 ~ "^" key "=" { print key "=" value; found = 1; next }
    { print }
    END { if (!found) print key "=" value }
  ' "$env_file" > "$temporary"
  mv "$temporary" "$env_file"
  echo "Generated $key"
}

random_hex() {
  openssl rand -hex "$1"
}

set_if_empty POSTGRES_PASSWORD "$(random_hex 24)"
set_if_empty COD_DB_PASSWORD "$(random_hex 24)"
set_if_empty N8N_DB_PASSWORD "$(random_hex 24)"
set_if_empty N8N_ENCRYPTION_KEY "$(random_hex 32)"
set_if_empty AUTH_SECRET "$(random_hex 32)"
set_if_empty ADMIN_PASSWORD "$(random_hex 16)"
set_if_empty INTERNAL_API_TOKEN "$(random_hex 32)"
set_if_empty ORDER_WEBHOOK_KEY "$(random_hex 32)"
set_if_empty LABEL_SIGNING_SECRET "$(random_hex 32)"

chmod 600 "$env_file"
echo "Secrets are ready in $env_file. Fill the remaining deployment values before starting the stack."
