#!/bin/sh
# rustelo-leptos-server — local installation wrapper
#
# Resolves the site root, sets required env vars, and exec's the real binary.
# Installed at $HOME/.local/bin/rustelo-leptos-server by `just local-install`.
#
# Site root resolution order:
#   1. --site <path>  (explicit workspace root containing site/)
#   2. $PWD has a site/ subdirectory
#   3. $HOME/.config/rustelo-leptos-server/ exists and has site/
#
# Any env var set in the caller environment is preserved (: "${VAR:=...}").
set -eu

REAL_BIN="$HOME/.local/libexec/rustelo-leptos-server"
NICKEL_BASE="$HOME/.local/share/rustelo/nickel"
CONFIG_HOME="$HOME/.config/rustelo-leptos-server"

# -- parse --site flag before forwarding remaining args to the 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

# -- site root resolution --------------------------------------------------
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 'rustelo-leptos-server: site root not found\n' >&2
        printf '  provide one of:\n' >&2
        printf '    --site <workspace>       workspace root that contains site/\n' >&2
        printf '    run from a dir with site/ subfolder\n' >&2
        printf '    place config at %s/site/\n' "$CONFIG_HOME" >&2
        exit 1
    fi
fi

# -- env setup (caller values take precedence) -----------------------------
: "${SITE_CONFIG_PATH:=$SITE_ROOT/site/config/index.ncl}"
: "${NICKEL_IMPORT_PATH:=$NICKEL_BASE:$SITE_ROOT/site/config}"
# Leptos serves static assets (pkg/, images, css) from LEPTOS_SITE_ROOT.
# For local use the deployed site tree lives at $SITE_ROOT/site; a dev build
# can point this at $SITE_ROOT/target/site instead.
: "${LEPTOS_SITE_ROOT:=$SITE_ROOT/site}"

export SITE_CONFIG_PATH NICKEL_IMPORT_PATH LEPTOS_SITE_ROOT

exec "$REAL_BIN" "$@"
