#!/bin/bash

# define placeholders
PLACEHOLDER_VAULT_KEY=__VAULT_KEY__
FILENAME_VAULT_OUTPUT=vaultSecrets.txt

set -euo pipefail

# Validation function: value in .env must not contain placeholders (like __SOME-KEY__)
validate_env_var() {
  local var_name="$1"
  local value="${!var_name:-}"

  if [[ -z "$value" ]]; then
    echo "Error: $var_name is not set or empty" >&2
    exit 1
  fi

  if [[ "$value" == __*__ ]]; then
    echo "- Error: $var_name contains a placeholder value ($value), you must run the 'createConnectorFiles' script first" >&2
    exit 1
  fi
}

echo ""
echo "Checking prerequisites..."
# fail early if .env does not exist, otherwise load variables from .env
if [ -f .env ]; then
  echo "   - .env file is available"
  POSTGRES_PASSWORD=$( grep -E '^POSTGRES_PASSWORD=' .env | cut -d '=' -f2- )
  POSTGRES_CONNECTOR_PASSWORD=$( grep -E '^POSTGRES_CONNECTOR_PASSWORD=' .env | cut -d '=' -f2- )
  EDC_IH_SUPERUSER_KEY=$( grep -E '^EDC_IH_SUPERUSER_KEY=' .env | cut -d '=' -f2- )
else
  echo "   - .env file not found" >&2
  exit 1
fi

# fail early if .env still contains placeholders
#echo "   - superuser-key is '$EDC_IH_SUPERUSER_KEY'"
#echo "   - connector password is '$POSTGRES_PASSWORD'"
#echo "   - connector password is '$POSTGRES_CONNECTOR_PASSWORD'"
validate_env_var EDC_IH_SUPERUSER_KEY
validate_env_var POSTGRES_PASSWORD
validate_env_var POSTGRES_CONNECTOR_PASSWORD

echo ""
echo "1. Initializing vault..."
docker compose up -d vault
sleep 3
docker compose exec vault sh -c "vault operator init -key-shares=5 -key-threshold=3" > $FILENAME_VAULT_OUTPUT
echo "   - stored vault keys into '$FILENAME_VAULT_OUTPUT'"

# get vault token from the output
VAULT_TOKEN=$( grep -E '^Initial Root Token: ' vaultSecrets.txt | cut -d ' ' -f4- )
# set vault token  into .env (replace $PLACEHOLDER_VAULT_KEY by $VAULT_TOKEN)
sed -i "s|$PLACEHOLDER_VAULT_KEY|$VAULT_TOKEN|g" .env
echo "   - extracted initial root token of vault ($VAULT_TOKEN) and set it into .env"

# extract unseal keys from the vault output and unseal the vault
UNSEAL_KEY_1=$( grep -E '^Unseal Key 1: ' vaultSecrets.txt | cut -d ' ' -f4- )
UNSEAL_KEY_2=$( grep -E '^Unseal Key 2: ' vaultSecrets.txt | cut -d ' ' -f4- )
UNSEAL_KEY_3=$( grep -E '^Unseal Key 3: ' vaultSecrets.txt | cut -d ' ' -f4- )
echo "   - extracted three unseal keys for vault (from $FILENAME_VAULT_OUTPUT)"
docker compose exec vault sh -c "export VAULT_TOKEN=$VAULT_TOKEN && vault operator unseal $UNSEAL_KEY_1 && vault operator unseal $UNSEAL_KEY_2 && vault operator unseal $UNSEAL_KEY_3"
echo "   - unsealed vault"
docker compose exec vault sh -c "export VAULT_TOKEN=$VAULT_TOKEN && vault secrets enable -path=secret kv-v2"
echo "   - enabled kv-v2 secrets engine"
docker compose exec vault sh -c "export VAULT_TOKEN=$VAULT_TOKEN && vault kv put secret/super-user-apikey content=\"$EDC_IH_SUPERUSER_KEY\""
echo "   - wrote superuser API key into vault"
echo ""
echo "   Finished initializing vault."
echo ""

echo "2. Initializing database..."
echo ""
docker compose up -d db
sleep 3
# run the commands from sql/setup-users.sql: pipe it into the container, so there is no need for a temporary volume
cat sql/setup-users.sql | docker compose exec -T -e PGPASSWORD=$POSTGRES_PASSWORD db psql -U postgres -a
echo "   - created users"
# similar for setup-healthcheck.sql
cat sql/setup-healthcheck.sql | docker compose exec -T -e PGPASSWORD=whateverBecauseOnlyUsedOnce db psql -U healthcheck -d healthcheck -a
echo "   - configured healthcheck user"
echo ""
echo "   Finished initializing database."
echo ""

# starting connector
echo "3. Starting connector..."
echo ""
docker compose up -d connector
echo "   - started connector"
echo ""
echo "Finished! The connector is now starting for its first time."
echo ""
echo "Return to README.md for instructions how to continue (or how to troubleshoot)"
