#!/bin/sh
set -eu

CONFIG_PATH="${APP_CONFIG:-/app/config/config.json}"
APPINFO_PATH="${APPINFO_PATH:-/app/config/APPINFO.json}"
DEFAULT_APPINFO="/app/default-config/APPINFO.json"
STANDARD_IMAGE_DIR="${STANDARD_IMAGE_DIR:-/app/app/static/uploads/library}"

mkdir -p "$(dirname "$CONFIG_PATH")" "$(dirname "$APPINFO_PATH")" "$STANDARD_IMAGE_DIR"
echo "Standard image library: $STANDARD_IMAGE_DIR"

if [ ! -f "$CONFIG_PATH" ]; then
    echo "Initializing AssetManager configuration: $CONFIG_PATH"
    python - "$CONFIG_PATH" <<'PY'
import json
import sys
from pathlib import Path
from app.config import DEFAULT_CONFIG

path = Path(sys.argv[1])
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("x", encoding="utf-8") as handle:
    json.dump(DEFAULT_CONFIG, handle, ensure_ascii=False, indent=2)
    handle.write("\n")
PY
else
    echo "Keeping existing AssetManager configuration: $CONFIG_PATH"
fi

if [ ! -f "$APPINFO_PATH" ]; then
    echo "Initializing AssetManager APPINFO: $APPINFO_PATH"
    cp "$DEFAULT_APPINFO" "$APPINFO_PATH"
else
    echo "Keeping existing AssetManager APPINFO: $APPINFO_PATH"
fi

exec "$@"
