#!/bin/sh
# Assemble the standalone download without requiring a build tool or runtime dependency.
set -eu
export LC_ALL=C

case "$#:${1:-}" in
    0:|1:--check) ;;
    *) printf 'Usage: sh scripts/msb-trust/build.sh [--check]\n' >&2; exit 2 ;;
esac

source_dir=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd)
output=$source_dir/msb-trust.sh
temporary=$(mktemp "$source_dir/.msb-trust.XXXXXX")
trap 'rm -f "$temporary"' EXIT
trap 'exit 1' HUP INT TERM

# Discover handlers in a stable order. Names become shell function prefixes.
applications=
for source in "$source_dir"/apps/*.sh; do
    [ -f "$source" ] || { printf 'No application handlers found\n' >&2; exit 1; }
    name=${source##*/}
    name=${name%.sh}
    case "$name" in
        ''|[!a-z]*|*[!a-z0-9_]*|all)
            printf 'Invalid application name: %s\n' "$name" >&2
            exit 1
            ;;
    esac
    applications="${applications:+$applications }$name"
done

{
    printf '#!/bin/sh\n'
    printf '# Generated by scripts/msb-trust/build.sh; edit scripts/msb-trust/ instead.\n'
    printf '# Explicit certificate setup for applications with their own trust stores.\n'
    printf 'set -eu\n\nSUPPORTED_APPLICATIONS="%s"\n\n' "$applications"
    cat "$source_dir/core.sh"
    for source in "$source_dir"/apps/*.sh; do
        printf '\n'
        cat "$source"
    done
} > "$temporary"

sh -n "$temporary"
# Source definitions only; never run certificate setup during assembly.
sh -eu -c '
    . "$1"
    for application in $SUPPORTED_APPLICATIONS; do
        for hook in tools packages help configure; do
            command -v "${application}_$hook" >/dev/null 2>&1 || {
                printf "Missing handler: %s_%s\n" "$application" "$hook" >&2
                exit 1
            }
        done
    done
' sh "$temporary"
printf '\nmain "$@"\n' >> "$temporary"

if [ "${1:-}" = --check ]; then
    cmp -s "$temporary" "$output" || {
        printf 'msb-trust.sh is out of date; run: sh scripts/msb-trust/build.sh\n' >&2
        exit 1
    }
else
    chmod 755 "$temporary"
    mv "$temporary" "$output"
fi
