#!/bin/sh
# hu13 container entrypoint (f0rge issue #11): build once, then serve.
#
# Layout: the repo is mounted read-only at /data/repo, the inbox lives at
# /data/inbox (OUTSIDE the served tree — serve refuses to start otherwise),
# the built site goes to /srv/www.
#
# Env:
#   HU13_BRANCH     branch to build (default: main/master auto-detect)
#   HU13_CLONE_URL  clone URL to advertise (default: repo origin remote)
#   HU13_PUBLIC_ORIGIN public base URL of this server (default: unset;
#                   when set, clone block advertises `<origin>/repo.git`)
#   HU13_REPO_NAME  repo display name (default: repo dir name; never blank)
#   HU13_DESCRIPTION
#                   site description (default: hidden, no empty <p>)
#   HU13_LISTEN     serve address (default: 0.0.0.0:39313)
#   HU13_MAX_TITLE / HU13_MAX_BODY / HU13_MAX_BYTES /
#   HU13_RATE_PER_HOUR / HU13_QUOTA
#                   inbox caps (serve defaults when unset; passed through
#                   as flags only when set, env is the fallback otherwise)
#
# Fail loud: any build failure (bad branch, bad repo, missing dir)
# aborts before serve starts. `serve` is exec'd so it keeps PID 1.
set -eu

# Mounted checkouts belong to the host uid, but we run as uid 10000:
# without this git refuses every read ("dubious ownership") and the
# build below would misreport "branch not found".
git config --global --add safe.directory /data/repo

# Build argv with "$@" (POSIX-safe: values with spaces/quotes survive).
set -- /data/repo -o /srv/www
if [ -n "${HU13_BRANCH:-}" ]; then
    set -- "$@" --branch "$HU13_BRANCH"
fi
if [ -n "${HU13_CLONE_URL:-}" ]; then
    set -- "$@" --clone-url "$HU13_CLONE_URL"
fi
if [ -n "${HU13_PUBLIC_ORIGIN:-}" ]; then
    set -- "$@" --public-origin "$HU13_PUBLIC_ORIGIN"
fi
if [ -n "${HU13_REPO_NAME:-}" ]; then
    set -- "$@" --repo-name "$HU13_REPO_NAME"
fi
if [ -n "${HU13_DESCRIPTION:-}" ]; then
    set -- "$@" --description "$HU13_DESCRIPTION"
fi
hu13 build "$@"

set -- --www /srv/www --inbox-dir /data/inbox \
    --listen "${HU13_LISTEN:-0.0.0.0:39313}"

if [ -n "${HU13_MAX_TITLE:-}" ]; then
    set -- "$@" --max-title "$HU13_MAX_TITLE"
fi
if [ -n "${HU13_MAX_BODY:-}" ]; then
    set -- "$@" --max-body "$HU13_MAX_BODY"
fi
if [ -n "${HU13_MAX_BYTES:-}" ]; then
    set -- "$@" --max-bytes "$HU13_MAX_BYTES"
fi
if [ -n "${HU13_RATE_PER_HOUR:-}" ]; then
    set -- "$@" --rate-per-hour "$HU13_RATE_PER_HOUR"
fi
if [ -n "${HU13_QUOTA:-}" ]; then
    set -- "$@" --quota "$HU13_QUOTA"
fi

exec hu13 serve "$@"
