#!/bin/sh -e
# genapkovl-mountaineer-server.sh — invoked by mkimage's build_apkovl()
# to produce <hostname>.apkovl.tar.gz in the current directory.
#
# This is the seam between mkimage's "give me one apkovl tarball" contract
# and Mountaineer's two-apkovl model (live and target). The flow:
#
#   1. Build the *target* apkovl (apkovl-src/common only).
#   2. Stage a dynamic extras directory containing:
#        usr/local/sbin/mountaineer-install   (the installer script)
#        usr/share/mountaineer/install.apkovl.tar.gz  (the target apkovl from step 1)
#        usr/share/mountaineer/docs/          (MANIFESTO, STACK, ROUTES, INSTALL)
#   3. Build the *live* apkovl by merging apkovl-src/common +
#      apkovl-src/live + the staged extras.
#   4. Emit as $HOSTNAME.apkovl.tar.gz in cwd (mkimage's contract).
#
# Reads MOUNTAINEER_SRC from environment (set by build.sh).

HOSTNAME="${1:?usage: $0 <hostname>}"

if [ -z "${MOUNTAINEER_SRC:-}" ]; then
    echo "error: MOUNTAINEER_SRC env var not set; build.sh should export it" >&2
    exit 1
fi

BUILD_APKOVL="$MOUNTAINEER_SRC/tools/build-apkovl.sh"
INSTALLER="$MOUNTAINEER_SRC/installer/install.sh"
SPEC_DIR="$MOUNTAINEER_SRC/../mountaineer"

for f in "$BUILD_APKOVL" "$INSTALLER"; do
    [ -x "$f" ] || { echo "error: missing or non-executable: $f" >&2; exit 1; }
done

work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT

target_apkovl="$work/target.apkovl.tar.gz"
extras="$work/extras"

echo "==> genapkovl: building target apkovl" >&2
"$BUILD_APKOVL" server-target "$target_apkovl" >&2

echo "==> genapkovl: staging live extras" >&2
mkdir -p "$extras/usr/local/sbin" "$extras/usr/share/mountaineer/docs"
cp "$INSTALLER" "$extras/usr/local/sbin/mountaineer-install"
chmod +x "$extras/usr/local/sbin/mountaineer-install"
cp "$target_apkovl" "$extras/usr/share/mountaineer/install.apkovl.tar.gz"

# Spec docs from the sibling repo, if present. Don't fail the build if
# they aren't (the build can run from a checkout that doesn't have them).
if [ -d "$SPEC_DIR" ]; then
    for doc in MANIFESTO.md STACK.md PROFILES.md ROUTES.md INSTALL.md BUILD-TOOLS.md; do
        [ -f "$SPEC_DIR/$doc" ] && cp "$SPEC_DIR/$doc" "$extras/usr/share/mountaineer/docs/"
    done
fi

echo "==> genapkovl: building live apkovl as $PWD/$HOSTNAME.apkovl.tar.gz" >&2
"$BUILD_APKOVL" server "$PWD/$HOSTNAME.apkovl.tar.gz" --extra "$extras" >&2
