#!/usr/bin/env sh
set -eu

APP_ENV_VALUE="${APP_ENV:-}"

case "$APP_ENV_VALUE" in
  production|prod)
    RULES_FILE="/etc/config/oathkeeper/rules.prod.json"
    ;;
  stage|staging)
    RULES_FILE="/etc/config/oathkeeper/rules.stage.json"
    ;;
  *)
    RULES_FILE="/etc/config/oathkeeper/rules.json"
    ;;
 esac

export RULES_FILE

echo "[oathkeeper] APP_ENV=$APP_ENV_VALUE rules=$RULES_FILE"

RULES_ACTIVE="/etc/config/oathkeeper/rules.active.json"
if [ ! -f "$RULES_FILE" ]; then
  echo "[oathkeeper] rules file not found: $RULES_FILE"
  exit 1
fi
cp "$RULES_FILE" "$RULES_ACTIVE"

LOG_DIR="/var/log/oathkeeper"
LOG_FILE="${LOG_DIR}/access.log"
mkdir -p "$LOG_DIR"
if ! touch "$LOG_FILE" 2>/dev/null; then
  echo "[oathkeeper] log file not writable: $LOG_FILE"
  ls -ld "$LOG_DIR" || true
  exit 1
fi

exec /bin/sh -c "oathkeeper serve proxy -c /etc/config/oathkeeper/oathkeeper.yml 2>&1 | tee \"$LOG_FILE\""
