#!/bin/sh
# Docker entrypoint for Nginx + PHP/Laravel
set -eu

# -------- defaults (override via env) --------
: "${APP_DIR:=/var/www/html}"
: "${NGINX_TEMPLATE:=/etc/nginx/templates/default.conf.template}"
: "${NGINX_HTTPD_DIR:=/etc/nginx/http.d}"
: "${NGINX_CONF_OUT:=${NGINX_HTTPD_DIR}/default.conf}"
: "${HTPASSWD_PATH:=/etc/nginx/htpasswd}"
: "${BASIC_AUTH_REALM:=Restricted Content}"
: "${SUPERVISOR_CONF:=/etc/supervisor/supervisord.conf}"

log() { printf '[entrypoint] %s\n' "$*"; }
err() { printf '[entrypoint][ERROR] %s\n' "$*" >&2; }
die() { err "$*"; exit 1; }
need() { command -v "$1" >/dev/null 2>&1 || die "Missing required command: $1"; }

# required tools
need envsubst; need nginx; need php; need supervisord

# server name
SERVER_NAME="${SERVER_NAME:-$(hostname -f 2>/dev/null || hostname 2>/dev/null || echo localhost)}"
export SERVER_NAME

# truthy helper
is_truthy() {
  case "${1:-}" in 1|true|TRUE|yes|YES|on|ON) return 0;; *) return 1;; esac
}

# -------- basic auth directives --------
BASIC_AUTH_DIRECTIVES=""
if is_truthy "${ENABLE_BASIC_AUTH:-}"; then
  log "Enabling basic authentication"
  [ -f "$HTPASSWD_PATH" ] || die "htpasswd not found: $HTPASSWD_PATH"
  BASIC_AUTH_DIRECTIVES=$(cat <<'EOF'
        auth_basic "__REALM__";
        auth_basic_user_file __HTPASSWD__;
EOF
)
  # safe placeholder substitution
  esc() { printf '%s' "$1" | sed 's/[&/\]/\\&/g'; }
  BASIC_AUTH_DIRECTIVES=$(printf '%s' "$BASIC_AUTH_DIRECTIVES" \
    | sed "s|__REALM__|$(esc "$BASIC_AUTH_REALM")|g" \
    | sed "s|__HTPASSWD__|$(esc "$HTPASSWD_PATH")|g")
else
  log "Basic authentication is disabled"
fi
export BASIC_AUTH_DIRECTIVES

# -------- render nginx config (atomic) --------
[ -f "$NGINX_TEMPLATE" ] || die "Missing template: $NGINX_TEMPLATE"
[ -d "$NGINX_HTTPD_DIR" ] || die "Missing nginx conf dir: $NGINX_HTTPD_DIR"

tmpconf="$(mktemp "${NGINX_CONF_OUT}.XXXXXX")"
envsubst '$SERVER_NAME,$BASIC_AUTH_DIRECTIVES' <"$NGINX_TEMPLATE" >"$tmpconf" \
  || die "envsubst failed"

mv -f "$tmpconf" "$NGINX_CONF_OUT"
log "Wrote nginx config -> $NGINX_CONF_OUT"

# final sanity test against active config tree
nginx -t || die "nginx config test failed after install"

# -------- Laravel cache clears (best-effort) --------
if [ -f "$APP_DIR/artisan" ]; then
  log "Clearing Laravel caches"
  ( cd "$APP_DIR" && php artisan config:clear || log "config:clear failed (continuing)" )
  ( cd "$APP_DIR" && php artisan cache:clear  || log "cache:clear failed (continuing)" )
else
  log "No Laravel app at $APP_DIR; skipping artisan"
fi

# -------- entrypoint behavior --------
# If the first arg is an option (starts with -), assume supervisord.
if [ "${1:-}" ] && [ "${1#-}" != "$1" ]; then
  set -- /usr/bin/supervisord -n -c "$SUPERVISOR_CONF" "$@"
fi

# If they provided a command (e.g., sh, bash, php -v), run it.
if [ "${1:-}" ] && [ "$1" != "/usr/bin/supervisord" ] && [ "$1" != "supervisord" ]; then
  log "Executing custom command: $*"
  exec "$@"
fi

# Default: start supervisord in the foreground (PID 1)
log "Starting supervisord"
exec /usr/bin/supervisord -n -c "$SUPERVISOR_CONF"
