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

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

IMAGE_NAME="${IMAGE_NAME:-beaver/authz-service:latest}"
CONTAINER_NAME="${CONTAINER_NAME:-beaver-authz-service}"
DATA_ROOT="${DATA_ROOT:-${SCRIPT_DIR}/runtime/data}"
HOST_PORT="${HOST_PORT:-19090}"
HOST_BIND_IP="${HOST_BIND_IP:-0.0.0.0}"
AUTHZ_ISSUER="${AUTHZ_ISSUER:-http://127.0.0.1:${HOST_PORT}}"
AUTHZ_INTERNAL_TOKEN="${AUTHZ_INTERNAL_TOKEN:-dev-internal-token}"
AUTHZ_ACCESS_TOKEN_TTL_SECONDS="${AUTHZ_ACCESS_TOKEN_TTL_SECONDS:-3600}"
DEPLOY_API_BASE_URL="${DEPLOY_API_BASE_URL:-http://127.0.0.1:8090}"
DEPLOY_API_TOKEN="${DEPLOY_API_TOKEN:-}"
FORCE_BUILD=0
REPLACE=0

usage() {
  cat <<'EOF'
Usage:
  ./start-authz.sh [--build] [--replace]
EOF
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --build)
      FORCE_BUILD=1
      shift
      ;;
    --replace)
      REPLACE=1
      shift
      ;;
    --help|-h)
      usage
      exit 0
      ;;
    *)
      printf '[start-authz] unknown argument: %s\n' "$1" >&2
      exit 1
      ;;
  esac
done

mkdir -p "${DATA_ROOT}"

if [[ "${FORCE_BUILD}" -eq 1 ]] || ! docker image inspect "${IMAGE_NAME}" >/dev/null 2>&1; then
  docker build -t "${IMAGE_NAME}" "${SCRIPT_DIR}"
fi

if docker container inspect "${CONTAINER_NAME}" >/dev/null 2>&1; then
  if [[ "${REPLACE}" -eq 1 ]]; then
    docker rm -f "${CONTAINER_NAME}" >/dev/null
  else
    printf '[start-authz] container already exists: %s\n' "${CONTAINER_NAME}" >&2
    exit 1
  fi
fi

docker run -d \
  --name "${CONTAINER_NAME}" \
  --restart unless-stopped \
  -p "${HOST_BIND_IP}:${HOST_PORT}:19090" \
  -v "${DATA_ROOT}:/var/lib/authz-service/data" \
  -e "AUTHZ_ISSUER=${AUTHZ_ISSUER}" \
  -e "AUTHZ_INTERNAL_TOKEN=${AUTHZ_INTERNAL_TOKEN}" \
  -e "AUTHZ_ACCESS_TOKEN_TTL_SECONDS=${AUTHZ_ACCESS_TOKEN_TTL_SECONDS}" \
  -e "DEPLOY_API_BASE_URL=${DEPLOY_API_BASE_URL}" \
  -e "DEPLOY_API_TOKEN=${DEPLOY_API_TOKEN}" \
  "${IMAGE_NAME}" >/dev/null

printf 'container_name=%s\n' "${CONTAINER_NAME}"
printf 'host_port=%s\n' "${HOST_PORT}"
printf 'data_root=%s\n' "${DATA_ROOT}"
