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

AUTHZ_HOST="${AUTHZ_HOST:-0.0.0.0}"
AUTHZ_PORT="${AUTHZ_PORT:-19090}"
AUTHZ_DATA_DIR="${AUTHZ_DATA_DIR:-/var/lib/authz-service/data}"
AUTHZ_PRIVATE_KEY_PATH="${AUTHZ_PRIVATE_KEY_PATH:-${AUTHZ_DATA_DIR}/signing_key.pem}"
AUTHZ_ISSUER="${AUTHZ_ISSUER:-http://127.0.0.1:${AUTHZ_PORT}}"
SEED_DATA_DIR="/opt/authz-service/seed-data"

mkdir -p "${AUTHZ_DATA_DIR}"

for file_name in backends.json backend_credentials.json permissions.json settings.json users.json; do
  if [[ ! -f "${AUTHZ_DATA_DIR}/${file_name}" ]]; then
    cp "${SEED_DATA_DIR}/${file_name}" "${AUTHZ_DATA_DIR}/${file_name}"
  fi
done

export AUTHZ_HOST AUTHZ_PORT AUTHZ_DATA_DIR AUTHZ_PRIVATE_KEY_PATH AUTHZ_ISSUER

exec uvicorn app.main:app --host "${AUTHZ_HOST}" --port "${AUTHZ_PORT}"
