#!/bin/sh
set -eu

for dir in \
  "$(dirname "${VENDOO_DB_PATH:-/app/data/db/vendoo.db}")" \
  "${VENDOO_UPLOADS_DIR:-/app/data/uploads}" \
  "${VENDOO_BACKUP_DIR:-/app/data/backups}" \
  "${VENDOO_OPERATIONS_DIR:-/app/data/operations}" \
  "${VENDOO_LOG_DIR:-/app/data/logs}" \
  "$(dirname "${VENDOO_CONFIG_PATH:-/app/data/config/vendoo.env}")" \
  "${VENDOO_MODULES_DIR:-/app/data/modules}"; do
  mkdir -p "$dir"
  test -w "$dir" || { echo "[FATAL] Kein Schreibzugriff auf $dir (Container-UID 1000)." >&2; exit 70; }
done

if [ "${NODE_ENV:-production}" = "production" ] && [ "${VENDOO_REQUIRE_SETUP_TOKEN:-true}" = "true" ]; then
  token="${VENDOO_SETUP_TOKEN:-}"
  if [ "${#token}" -lt 32 ]; then
    echo "[FATAL] VENDOO_SETUP_TOKEN muss im Produktionsbetrieb mindestens 32 Zeichen lang sein." >&2
    exit 78
  fi
fi

if [ "${VENDOO_TRUST_PROXY:-false}" != "false" ] && [ -z "${PUBLIC_BASE_URL:-}" ]; then
  echo "[WARN] VENDOO_TRUST_PROXY ist aktiv, aber PUBLIC_BASE_URL fehlt. HTTPS-/Cookie-Erkennung sorgfältig prüfen." >&2
fi

exec "$@"
