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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
OUTPUT_DIR="${ORY_CONFIG_OUTPUT_DIR:-$ROOT_DIR/config/.generated/ory}"
TEMPLATE_ROOT="${ORY_CONFIG_TEMPLATE_ROOT:-$ROOT_DIR/docker/ory}"

load_env_file() {
  local env_file="$1"
  if [[ -f "$env_file" ]]; then
    set -a
    # shellcheck disable=SC1090
    source "$env_file"
    set +a
  fi
}

fail() {
  echo "[ory-config] ERROR: $1" >&2
  exit 1
}

render_template() {
  local src="$1"
  local dst="$2"
  mkdir -p "$(dirname "$dst")"
  perl -pe '
    s/\$\{([A-Za-z_][A-Za-z0-9_]*)(:-([^}]*))?\}/
      exists $ENV{$1} ? $ENV{$1} : defined $3 ? $3 : die "missing env var: $1\n"
    /gex
  ' "$src" > "$dst"
}

copy_if_exists() {
  local src="$1"
  local dst="$2"
  if [[ -e "$src" ]]; then
    mkdir -p "$(dirname "$dst")"
    cp -a "$src" "$dst"
  fi
}

json_array_to_lines() {
  local json="$1"
  local newline=$'\n'
  json="${json//$'\n'/}"
  json="${json#\[}"
  json="${json%\]}"
  json="${json//\",\"/$newline}"
  json="${json//\"/}"
  json="${json//,/$newline}"
  printf '%s\n' "$json" | sed '/^[[:space:]]*$/d'
}

append_unique_url() {
  local candidate="${1:-}"
  [[ -n "$candidate" ]] || return 0
  local existing
  for existing in "${KRATOS_ALLOWED_RETURN_URLS[@]}"; do
    [[ "$existing" == "$candidate" ]] && return 0
  done
  KRATOS_ALLOWED_RETURN_URLS+=("$candidate")
}

url_host() {
  local url="${1:-}"
  [[ -n "$url" ]] || return 0

  local without_scheme="$url"
  if [[ "$without_scheme" == *"://"* ]]; then
    without_scheme="${without_scheme#*://}"
  fi
  without_scheme="${without_scheme%%/*}"
  without_scheme="${without_scheme%%\?*}"
  without_scheme="${without_scheme%%#*}"

  if [[ "$without_scheme" == \[*\]* ]]; then
    without_scheme="${without_scheme#[}"
    without_scheme="${without_scheme%%]*}"
  elif [[ "$without_scheme" == *:* ]]; then
    without_scheme="${without_scheme%%:*}"
  fi

  printf '%s' "$without_scheme"
}

resolve_kratos_session_cookie_domain() {
  if [[ -n "${KRATOS_SESSION_COOKIE_DOMAIN:-}" ]]; then
    export KRATOS_SESSION_COOKIE_DOMAIN
    return 0
  fi

  local public_host
  public_host="$(url_host "${KRATOS_BROWSER_URL:-}")"
  if [[ -z "$public_host" ]]; then
    public_host="$(url_host "${KRATOS_UI_URL:-}")"
  fi

  case "$public_host" in
    localhost|127.0.0.1|0.0.0.0|*.localhost)
      KRATOS_SESSION_COOKIE_DOMAIN="localhost"
      ;;
    *.hmac.kr|hmac.kr)
      KRATOS_SESSION_COOKIE_DOMAIN="hmac.kr"
      ;;
    "")
      KRATOS_SESSION_COOKIE_DOMAIN="localhost"
      ;;
    *)
      KRATOS_SESSION_COOKIE_DOMAIN="$public_host"
      ;;
  esac

  export KRATOS_SESSION_COOKIE_DOMAIN
}

build_kratos_allowed_return_urls_yaml() {
  KRATOS_ALLOWED_RETURN_URLS=()
  if [[ -n "${KRATOS_ALLOWED_RETURN_URLS_JSON:-}" ]]; then
    while IFS= read -r allowed_url; do
      append_unique_url "$allowed_url"
    done < <(json_array_to_lines "$KRATOS_ALLOWED_RETURN_URLS_JSON")
  fi

  if [[ ${#KRATOS_ALLOWED_RETURN_URLS[@]} -eq 0 ]]; then
    local kratos_ui="${KRATOS_UI_URL:-http://localhost:5000}"
    local userfront="${USERFRONT_URL:-http://localhost:5000}"
    local adminfront="${ADMINFRONT_URL:-http://localhost:5173}"
    local devfront="${DEVFRONT_URL:-http://localhost:5174}"
    local orgfront="${ORGFRONT_URL:-http://localhost:5175}"

    append_unique_url "$kratos_ui"
    append_unique_url "$kratos_ui/"
    append_unique_url "$userfront"
    append_unique_url "$userfront/"
    append_unique_url "$userfront/ko"
    append_unique_url "$userfront/ko/"
    append_unique_url "$userfront/en"
    append_unique_url "$userfront/en/"
    append_unique_url "$userfront/auth/callback"
    append_unique_url "$userfront/ko/auth/callback"
    append_unique_url "$userfront/en/auth/callback"
    append_unique_url "$adminfront/auth/callback"
    append_unique_url "$devfront/auth/callback"
    append_unique_url "$orgfront/auth/callback"
  fi

  if [[ -n "${KRATOS_ALLOWED_RETURN_URLS_EXTRA:-}" ]]; then
    IFS=',' read -r -a extra_urls <<<"$KRATOS_ALLOWED_RETURN_URLS_EXTRA"
    local extra_url
    for extra_url in "${extra_urls[@]}"; do
      extra_url="$(printf '%s' "$extra_url" | xargs)"
      append_unique_url "$extra_url"
    done
  fi

  if [[ ${#KRATOS_ALLOWED_RETURN_URLS[@]} -eq 0 ]]; then
    fail "Kratos allowed_return_urls is empty"
  fi

  KRATOS_ALLOWED_RETURN_URLS_YAML="$(
    printf '%s\n' "${KRATOS_ALLOWED_RETURN_URLS[@]}" | sed 's/^/        - /'
  )"
  export KRATOS_ALLOWED_RETURN_URLS_YAML
}

if [[ -n "${ORY_CONFIG_ENV_FILES:-}" ]]; then
  IFS=':' read -r -a env_files <<<"$ORY_CONFIG_ENV_FILES"
  for env_file in "${env_files[@]}"; do
    load_env_file "$env_file"
  done
else
  load_env_file "$ROOT_DIR/.env"
  load_env_file "$ROOT_DIR/config/.generated/auth-config.env"
fi

ORY_POSTGRES_USER="${ORY_POSTGRES_USER:-ory}"
ORY_POSTGRES_PASSWORD="${ORY_POSTGRES_PASSWORD:-secret}"
KRATOS_DB="${KRATOS_DB:-ory_kratos}"
HYDRA_DB="${HYDRA_DB:-ory_hydra}"
KETO_DB="${KETO_DB:-ory_keto}"
KRATOS_DSN="${KRATOS_DSN:-postgres://${ORY_POSTGRES_USER}:${ORY_POSTGRES_PASSWORD}@postgres_ory:5432/${KRATOS_DB}?sslmode=disable&max_conns=20}"
HYDRA_DSN="${HYDRA_DSN:-postgres://${ORY_POSTGRES_USER}:${ORY_POSTGRES_PASSWORD}@postgres_ory:5432/${HYDRA_DB}?sslmode=disable&max_conns=20}"
KETO_DSN="${KETO_DSN:-postgres://${ORY_POSTGRES_USER}:${ORY_POSTGRES_PASSWORD}@postgres_ory:5432/${KETO_DB}?sslmode=disable&max_conns=20}"
HYDRA_SYSTEM_SECRET="${HYDRA_SYSTEM_SECRET:-${SECRETS_SYSTEM:-${ORY_POSTGRES_PASSWORD}}}"
OATHKEEPER_INTROSPECT_CLIENT_ID="${OATHKEEPER_INTROSPECT_CLIENT_ID:-oathkeeper-introspect}"
OATHKEEPER_INTROSPECT_CLIENT_SECRET="${OATHKEEPER_INTROSPECT_CLIENT_SECRET:-oathkeeper-secret}"

export KRATOS_DSN HYDRA_DSN KETO_DSN HYDRA_SYSTEM_SECRET
export OATHKEEPER_INTROSPECT_CLIENT_ID OATHKEEPER_INTROSPECT_CLIENT_SECRET

resolve_kratos_session_cookie_domain
build_kratos_allowed_return_urls_yaml

mkdir -p "$OUTPUT_DIR/kratos" "$OUTPUT_DIR/hydra" "$OUTPUT_DIR/keto" "$OUTPUT_DIR/oathkeeper"

render_template "$TEMPLATE_ROOT/kratos/kratos.yml.template" "$OUTPUT_DIR/kratos/kratos.yml"
copy_if_exists "$TEMPLATE_ROOT/kratos/identity.schema.json" "$OUTPUT_DIR/kratos/identity.schema.json"
copy_if_exists "$TEMPLATE_ROOT/kratos/courier-http.jsonnet" "$OUTPUT_DIR/kratos/courier-http.jsonnet"
if [[ -d "$TEMPLATE_ROOT/kratos/courier-templates" ]]; then
  mkdir -p "$OUTPUT_DIR/kratos"
  rm -rf "$OUTPUT_DIR/kratos/courier-templates"
  cp -a "$TEMPLATE_ROOT/kratos/courier-templates" "$OUTPUT_DIR/kratos/courier-templates"
fi

render_template "$TEMPLATE_ROOT/hydra/hydra.yml.template" "$OUTPUT_DIR/hydra/hydra.yml"

render_template "$TEMPLATE_ROOT/keto/keto.yml.template" "$OUTPUT_DIR/keto/keto.yml"
copy_if_exists "$TEMPLATE_ROOT/keto/namespaces.ts" "$OUTPUT_DIR/keto/namespaces.ts"
copy_if_exists "$TEMPLATE_ROOT/keto/namespaces.yml" "$OUTPUT_DIR/keto/namespaces.yml"

render_template "$TEMPLATE_ROOT/oathkeeper/oathkeeper.yml.template" "$OUTPUT_DIR/oathkeeper/oathkeeper.yml"
copy_if_exists "$TEMPLATE_ROOT/oathkeeper/entrypoint.sh" "$OUTPUT_DIR/oathkeeper/entrypoint.sh"
chmod +x "$OUTPUT_DIR/oathkeeper/entrypoint.sh"
find "$OUTPUT_DIR/oathkeeper" -maxdepth 1 -type f -name 'rules*.json' -delete
for rules_file in "$TEMPLATE_ROOT"/oathkeeper/rules*.json; do
  [[ -e "$rules_file" ]] || continue
  copy_if_exists "$rules_file" "$OUTPUT_DIR/oathkeeper/$(basename "$rules_file")"
done

if find "$OUTPUT_DIR" -type f \( -name '*.yml' -o -name '*.yaml' -o -name '*.json' -o -name '*.toml' \) -print0 | xargs -0 grep -n '\${' >/tmp/ory-render-unresolved.$$ 2>/dev/null; then
  cat /tmp/ory-render-unresolved.$$ >&2
  rm -f /tmp/ory-render-unresolved.$$
  fail "rendered Ory config contains unresolved placeholders"
fi
rm -f /tmp/ory-render-unresolved.$$

echo "[ory-config] wrote: $OUTPUT_DIR"
