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

APP_ENV="${APP_ENV:-production}"
APP_ID="${APP_ID:-}"

if [ -z "${APP_ID}" ]; then
  if command -v uuidgen >/dev/null 2>&1; then
    APP_ID="$(uuidgen)"
  else
    APP_ID="$(python3 - <<'PY'
import uuid
print(uuid.uuid4())
PY
)"
  fi
fi

ENV_FILE="/var/www/.env"
if [ ! -f "${ENV_FILE}" ]; then
  cat > "${ENV_FILE}" <<EOF
APP_ENV=${APP_ENV}
APP_ID=${APP_ID}
DEBUG_TOOLS_ENABLED=${DEBUG_TOOLS_ENABLED:-false}
ALLOW_DB_RESET=${ALLOW_DB_RESET:-false}
WORKER_SLEEP_SECONDS=${WORKER_SLEEP_SECONDS:-2}

DB_HOST=${DB_HOST:-db}
DB_PORT=${DB_PORT:-3306}
DB_NAME=${DB_NAME:-scmedia}
DB_USER=${DB_USER:-scmedia}
DB_PASS=${DB_PASS:-changeme}

PATH_INCOMING=${PATH_INCOMING:-/data/incoming}
PATH_MOVIES=${PATH_MOVIES:-/data/movies}
PATH_SERIES=${PATH_SERIES:-/data/series}

VIDEO_EXT=${VIDEO_EXT:-mkv,mp4,avi,mov,m4v,ts,m2ts,wmv}
SCANNER_MAX_DEPTH=${SCANNER_MAX_DEPTH:-3}
SCANNER_MAX_FILES_PER_ITEM=${SCANNER_MAX_FILES_PER_ITEM:-3000}
EOF
fi

if [ "${AUTO_INIT_DB:-1}" = "1" ]; then
  bash /var/www/docker/scripts/init-db.sh
fi

exec "$@"
