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

CONFIG_DIR="${CONFIG_DIR:-/config}"
PORT="${PORT:-8080}"
ASTER_DEVICE="${ASTER_DEVICE:-}"
ASTER_USB="${ASTER_USB:-}"
ASTER_SIMULATE="${ASTER_SIMULATE:-0}"
ASTER_WRITE_ONLY="${ASTER_WRITE_ONLY:-0}"
ASTER_DISABLE_DISPLAY="${ASTER_DISABLE_DISPLAY:-0}"

mkdir -p "${CONFIG_DIR}" "${CONFIG_DIR}/img"

ARGS=(
  "--config-dir" "${CONFIG_DIR}"
  "--bind" "0.0.0.0:${PORT}"
)

if [[ -n "${ASTER_DEVICE}" ]]; then
  ARGS+=("--device" "${ASTER_DEVICE}")
fi

if [[ -n "${ASTER_USB}" ]]; then
  ARGS+=("--usb" "${ASTER_USB}")
fi

if [[ "${ASTER_SIMULATE}" == "1" ]]; then
  ARGS+=("--simulate")
fi

if [[ "${ASTER_WRITE_ONLY}" == "1" ]]; then
  ARGS+=("--write-only")
fi

if [[ "${ASTER_DISABLE_DISPLAY}" == "1" ]]; then
  ARGS+=("--disable-display")
fi

echo "Starting aster-webui native container"
echo "Config directory: ${CONFIG_DIR}"
echo "WebUI port: ${PORT}"
echo "Display mode: $(
  if [[ "${ASTER_DISABLE_DISPLAY}" == "1" ]]; then
    printf '%s' 'disabled'
  elif [[ "${ASTER_SIMULATE}" == "1" ]]; then
    printf '%s' 'simulate'
  elif [[ -n "${ASTER_DEVICE}" ]]; then
    printf 'device:%s' "${ASTER_DEVICE}"
  elif [[ -n "${ASTER_USB}" ]]; then
    printf 'usb:%s' "${ASTER_USB}"
  else
    printf '%s' 'default-usb'
  fi
)"

APP_PID=""

shutdown() {
  if [[ -n "${APP_PID}" ]] && kill -0 "${APP_PID}" >/dev/null 2>&1; then
    kill -TERM "${APP_PID}" >/dev/null 2>&1 || true
    wait "${APP_PID}" || true
  fi
}

trap shutdown INT TERM

/usr/local/bin/aster-webui "${ARGS[@]}" &
APP_PID="$!"
wait "${APP_PID}"
