#!/bin/bash

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 "   - Variable $var_name is ok (value: '$value')"
}

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_CONNECTOR_PASSWORD=$( grep -E '^POSTGRES_CONNECTOR_PASSWORD=' .env | cut -d '=' -f2- )
  echo "   - have extracted variables from .env"
else
  echo "   - .env file not found" >&2
  exit 1
fi

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

echo ""
echo "4. Initializing connector: setting super-user"
# create entry for super-user in database, but only if it does not exist already
countSuperUserEntries=$(
  docker compose exec -e PGPASSWORD=POSTGRES_CONNECTOR_PASSWORD db psql -U connector -d connector -x -c "SELECT COUNT(*) FROM public.participant_context;"
)
# this gives "-[ RECORD 1 ] count | 0" (if no entry) or "-[ RECORD 1 ] count | 1" (if one entry, meaning that the script has already been run)
numEntries=$( echo $countSuperUserEntries | grep 'count' | cut -d '|' -f2- | tr -d '[:blank:]' )
# now numEntries should contain 0 or 1, if the database query could be done, is empty otherwise
if [[ -z "$numEntries" ]]; then
  echo "   - Error: could not query database, maybe it is not running" >&2
#  exit 2
fi
# create super-user entry, but only if database table has 0 entries
if [[ $numEntries == 0 ]]; then
  TIMESTAMP_MS=$(date +%s%3N)
  #echo "   - timestamp for now is $TIMESTAMP_MS"
  docker compose exec -e PGPASSWORD="$POSTGRES_CONNECTOR_PASSWORD" db psql -U connector -d connector -c "INSERT INTO public.participant_context (participant_context_id, created_date, last_modified_date, state, api_token_alias, did, roles, properties) VALUES ('super-user', $TIMESTAMP_MS, $TIMESTAMP_MS, 1, 'super-user-apikey', 'did:web:super-user', '[\"admin\"]', '{}');"
  echo "   - created database entry for admin (super-user-apikey)"
else
  echo "   - not created database entry (there was already one)"
fi

echo ""
echo "5. starting nginx"
docker compose up -d nginx
echo "   - nginx started"
echo ""
echo "Finished! The connector is now running."
echo ""
echo "Next step: run http-requests to finish connector initialization - see README."
echo ""