#!/bin/sh
# content_processor — local installation wrapper
#
# Generates content indexes (index.json + per-post html/json + filter indexes)
# from a site's markdown under site/content/, written to site/public/r — the real
# tree distro.ncl packs to the PV, which the pod's site/r symlink serves.
#
# Installed at $HOME/.local/bin/content_processor by `just local-install`.
#
# Site root resolution (same as rustelo-htmx-server):
#   1. --site <path>   explicit workspace root containing site/
#   2. $PWD has a site/ subdirectory
#   3. $HOME/.config/rustelo-htmx-server/ has site/
#
# All remaining args are forwarded to the real binary
# (e.g. --content-type blog, --language en, --watch).
set -eu

REAL_BIN="$HOME/.local/libexec/content_processor"
CONFIG_HOME="$HOME/.config/rustelo-htmx-server"

SITE_ROOT=""
while [ $# -gt 0 ]; do
    case "$1" in
        --site|-s)   SITE_ROOT="$2"; shift 2 ;;
        --site=*)    SITE_ROOT="${1#*=}"; shift ;;
        *) break ;;
    esac
done

if [ -z "$SITE_ROOT" ]; then
    if [ -d "$PWD/site" ]; then
        SITE_ROOT="$PWD"
    elif [ -d "$CONFIG_HOME/site" ]; then
        SITE_ROOT="$CONFIG_HOME"
    else
        printf 'content_processor: site root not found\n' >&2
        printf '  provide --site <workspace>, run from a dir with site/, or use %s/site/\n' "$CONFIG_HOME" >&2
        exit 1
    fi
fi

# Output static_output = SITE_PUBLIC_PATH/SITE_SERVER_ROOT_CONTENT = site/public/r.
# This is the REAL shipped tree: distro.ncl `content_hot` packs site/public, and the
# deployed pod symlinks site/r -> public/r (organize-artifacts.sh), so the server's
# SITE_SERVER_CONTENT_ROOT=site/r resolves here. Writing to a bare site/r instead
# would land outside the packed tree and never reach the PV. Matches the binary's own
# default (SITE_PUBLIC_PATH=site/public). Caller env still wins.
: "${SITE_CONTENT_PATH:=$SITE_ROOT/site/content}"
: "${SITE_PUBLIC_PATH:=$SITE_ROOT/site/public}"
: "${SITE_SERVER_ROOT_CONTENT:=r}"

export SITE_CONTENT_PATH SITE_PUBLIC_PATH SITE_SERVER_ROOT_CONTENT

exec "$REAL_BIN" "$@"
