#!/bin/sh
# dsl41-launch -- the nightbank engine's command line, in one reviewed place.
#
# An example, not package data (DL-218). Every path and name below is
# synthetic. Copy this file, edit the block marked CONFIGURATION, and review
# the edit as you would review code: the run root, ACTIVE, ENVIRONMENT,
# PROPERTIES and every run option, with the release manifest's files, their
# ORDER and its layers, are what a resume is gated on (deployment-runbook ss5). The two units beside this file call it; the
# only thing they repeat is the run root's RequiresMountsFor=.
#
# The estate is the application's release, and this file holds only the
# infrastructure's facts (DL-407). Under the site's estate directory,
# ESTATE_RELEASES holds one directory per release, installed whole and never
# changed: its JIL, its calendars, its properties layers and its manifest,
# estate.toml. A release directory is never a symlink: the bundle hash covers
# each input's path string, so the opener must name the same paths the seal
# named (period-model ss1.1). ACTIVE is a plain text file, not a symlink, whose
# one line names the active release. The engine mode takes the estate's files, layers, timezone and
# semantics from the active release's manifest through `dsl41 estate args`,
# so a JIL release never edits this file. The site's own properties file,
# PROPERTIES, follows the manifest's layers as one more -p, so the site's
# values override the application's. A missing, symlinked, empty or
# multi-line ACTIVE, or a release that is a symlink or holds no estate.toml,
# refuses the start.
#
#   dsl41-launch engine              exec `dsl41 run` on the configured root
#   dsl41-launch supervisor          exec `dsl41 supervise start` on that root
#   dsl41-launch supervisor-ready    wait until the supervisor answers LIST
#   dsl41-launch supervisor-stop     SIGTERM the unit's MAINPID and wait for its exit
#   dsl41-launch --print [MODE]      print MODE's command, shell-quoted, and
#                                    run no estate command (MODE defaults to
#                                    engine; it runs the --supervisor probe)
#   dsl41-launch vars                print the CONFIGURATION the release verbs
#                                    read, one NAME=VALUE line each, the
#                                    value shell-quoted, and run nothing
#
# The engine mode passes --resume if and only if the run root holds its
# sentinel, <root>/journal.jsonl (deployment-runbook ss3). It chooses a
# genesis only for a root that does not exist or holds nothing but a
# supervisor's own files (shape 1's supervisor unit creates the root first)
# and what dsl41 stages before a genesis, catalogs/ and periods/.staging/
# (period-model ss1.1; a start that found no supervisor leaves them),
# and only while ESTATE_ANCHOR holds no anchor.json: a lineage that exists
# is opened through the trigger below, never started again by a genesis.
#
# One exception opens a root instead: the one-shot open trigger, an empty
# file at <RUN_ROOT>.open-from that the operator creates (deployment-runbook
# ss7, row 2). While it exists, the engine mode passes
# `--open-from ESTATE_ANCHOR`: the physical roll into RUN_ROOT, or the
# identical retry of a roll that stopped after it wrote the root's sentinel.
# The engine mode removes the trigger just before it execs dsl41, so every
# later start of the unit resumes the opened root. If that open fails, the
# unit stays failed: fix the cause, create the trigger again, start the unit.
# An opener that died before the root's sentinel leaves a restart with no
# trigger and no sentinel, and that start refuses with exit 2 because the
# anchor exists; the same recovery applies.
# --print shows the opener's line and leaves the trigger in place.
# A root it cannot read, or one with other contents and no sentinel, is
# refused: a missing mount or a lost sentinel must not become a fresh
# estate. dsl41 itself refuses a genesis on a root or anchor that holds an
# estate. The script then EXECS dsl41, so the service manager sees dsl41's
# own exit code and nothing here can fall back to a new estate, another
# root or the next period after a refusal.
#
# Exit 2 is this script's own configuration refusal, the code dsl41 uses
# for one, so the units' RestartPreventExitStatus covers both.

set -eu

# ---- CONFIGURATION ---------------------------------------------------------
# The install prefix: the runtime is the venv its .venv link selects
# (deployment-runbook ss7).
PREFIX=/opt/dsl41
DSL41=$PREFIX/.venv/bin/dsl41
# One estate's run root. A new baseline in a fresh root is an operator's
# edit of this line, never an automatic choice (deployment-runbook ss6).
RUN_ROOT=/srv/dsl41/runs/nightbank-01
# The LINEAGE anchor: genesis creates it here. After a physical roll,
# RUN_ROOT changes and this line does not (deployment-runbook ss6a).
ESTATE_ANCHOR=/srv/dsl41/runs/nightbank-01.anchor
# Always passed. A configured map that is missing or invalid makes
# `dsl41 run` refuse with exit 2; an omitted one would bring the engine up
# with no perimeter (deployment-runbook ss4, ss5).
ACCESS_MAP=/etc/dsl41/nightbank-access.toml
# The application's releases, and the file that names the active one
# (see the header).
ESTATE_RELEASES=/srv/dsl41/nightbank/releases
ACTIVE=/srv/dsl41/nightbank/active
# The manifest environment this host runs: its layers follow the manifest's
# own (DL-407).
ENVIRONMENT=wargame
# The site's properties, generated at install; the last -p, so they win.
PROPERTIES=/srv/dsl41/nightbank/night/night.properties
# The workload the units' limits were sized for: the supervisor unit's
# TimeoutStopSec=900 covers 15 + 5 + MAX_GRACE_S + 2 + 8 x MAX_JOBS + 10
# seconds (DL-401). `vars` prints them, and `dsl41 release prepare` refuses
# a release above them (DL-407, DL-412).
MAX_JOBS=107
MAX_GRACE_S=10
# The units' User= and the engine unit's name. The release verbs seal as that
# account through sudo and start that unit; `vars` prints both (DL-412).
SERVICE_ACCOUNT=dsl41
ENGINE_UNIT=dsl41-engine.service

# The engine's options after the estate's words, shell-quoted; a SUPERVISOR
# mode follows --detached. Their deployment half, --detached, --deadman,
# --as-machine and --machine-policy, is what every seal restates as --next-*,
# because an omitted --next-* option takes its default; `vars` prints it in
# that form (DL-407, deployment-runbook ss6a).
run_options() { # run_options [SUPERVISOR]
    quote_all -p "$PROPERTIES" \
        --run-root "$RUN_ROOT" \
        --estate-anchor "$ESTATE_ANCHOR" \
        --detached \
        ${1:+--supervisor "$1"} \
        --as-machine localhost \
        --machine-policy strict \
        --access-map "$ACCESS_MAP"
}

engine_command() {
    # The engine attaches to the supervisor unit's supervisor and never forks
    # its own (DL-396). A rollback onto a release before DL-396 keeps this
    # launcher, and that release has no --supervisor: it gets its supervisor
    # as it always did. The option's parse decides, by exit code: 0 passes
    # it, 2 (no such option) omits it, and anything else refuses (DL-402).
    [ -x "$DSL41" ] || refuse "$DSL41 is not executable"
    probe=0
    "$DSL41" run --supervisor attach --help >/dev/null 2>&1 || probe=$?
    case $probe in
        0) supervisor=attach ;;
        2) supervisor= ;;
        *) refuse "$DSL41 run --supervisor attach --help exited $probe: cannot tell attach from spawn" ;;
    esac
    # The estate's words come from the active release's manifest, in its
    # order, which is hashed (DL-407). A runtime without `estate args` is
    # before 1.13.0, and a rollback to it brings the launcher of its site
    # package; the parse decides by exit code, as for --supervisor (DL-402).
    probe=0
    "$DSL41" estate args --help >/dev/null 2>&1 || probe=$?
    case $probe in
        0) ;;
        2) refuse "this launcher needs dsl41 1.13.0 or later; a rollback below it reinstalls the site package qualified with that release" ;;
        *) refuse "$DSL41 estate args --help exited $probe: cannot tell whether it reads a manifest" ;;
    esac
    release=$(active_release) || exit $?
    ESTATE=$ESTATE_RELEASES/$release
    estate=$("$DSL41" estate args "$ESTATE/estate.toml" --for run \
        --environment "$ENVIRONMENT") ||
        refuse "$DSL41 estate args exited $? for $ESTATE/estate.toml"
    options=$(run_options "$supervisor")
    eval "set -- $options"
    opener=$(root_opener) || exit $?
    case $opener in
        resume) set -- "$@" --resume ;;
        open-from) set -- "$@" --open-from "$ESTATE_ANCHOR" ;;
    esac
    printf '%s %s %s' "$(quote_all "$DSL41" run)" "$estate" "$(quote_all "$@")"
}
# ---- end of CONFIGURATION --------------------------------------------------

# the one-shot open trigger (see the header)
OPEN_TRIGGER=$RUN_ROOT.open-from

# The active release's name: the one line of ACTIVE, one directory name
# under ESTATE_RELEASES that holds estate.toml (see the header, DL-407).
active_release() {
    [ -e "$ACTIVE" ] || [ -L "$ACTIVE" ] || refuse "$ACTIVE is missing: no release is active"
    [ ! -L "$ACTIVE" ] || refuse "$ACTIVE is a symlink: name the release in a plain file"
    [ -f "$ACTIVE" ] || refuse "$ACTIVE is not a file"
    name=$(cat "$ACTIVE") || refuse "cannot read $ACTIVE"
    case $name in
        '') refuse "$ACTIVE is empty: no release is active" ;;
        *"$NEWLINE"*) refuse "$ACTIVE holds more than one line: name one release" ;;
        . | .. | */*) refuse "$ACTIVE names '$name', which is not one directory name" ;;
    esac
    [ ! -L "$ESTATE_RELEASES/$name" ] ||
        refuse "$ESTATE_RELEASES/$name is a symlink: the opener must name the paths the seal named"
    [ -f "$ESTATE_RELEASES/$name/estate.toml" ] ||
        refuse "$ESTATE_RELEASES/$name holds no estate.toml: not a release"
    printf '%s\n' "$name"
}
NEWLINE='
'

# genesis or resume, decided from the run root alone, unless the one-shot
# open trigger exists; anything else refuses
root_opener() {
    if [ -e "$RUN_ROOT" ] || [ -L "$RUN_ROOT" ]; then
        [ -d "$RUN_ROOT" ] || refuse "$RUN_ROOT exists and is not a directory"
        if [ ! -r "$RUN_ROOT" ] || [ ! -x "$RUN_ROOT" ]; then
            refuse "$RUN_ROOT is not readable and searchable by $(id -un): cannot tell a resume from a genesis"
        fi
    fi
    if [ -e "$OPEN_TRIGGER" ] || [ -L "$OPEN_TRIGGER" ]; then
        echo open-from
        return
    fi
    if [ ! -e "$RUN_ROOT" ] && [ ! -L "$RUN_ROOT" ]; then
        genesis
        return
    fi
    if [ -e "$RUN_ROOT/journal.jsonl" ]; then
        echo resume
        return
    fi
    for entry in "$RUN_ROOT"/* "$RUN_ROOT"/.[!.]* "$RUN_ROOT"/..?*; do
        [ -e "$entry" ] || [ -L "$entry" ] || continue # an unmatched glob
        case ${entry##*/} in
            # Cold provisioning creates only an empty regular lock (DL-390).
            leader.lock)
                [ -f "$entry" ] && [ ! -L "$entry" ] && [ ! -s "$entry" ] \
                    || refuse "$entry is not an empty provisioned lock: inspect the root"
                ;;
            # what `dsl41 supervise start` puts in a root before any estate
            supervisor.lock | supervisor.log | supervisor.pid | supervisor.sock | .s.*) ;;
            # what `dsl41 run` stages before its genesis; dsl41 tolerates
            # both there (period-model ss1.1), so a start refused before the
            # sentinel, such as one that found no supervisor, retries
            catalogs)
                [ -d "$entry" ] && [ ! -L "$entry" ] \
                    || refuse "$entry is not a directory: inspect the root"
                ;;
            periods)
                [ -d "$entry" ] && [ ! -L "$entry" ] \
                    || refuse "$entry is not a directory: inspect the root"
                for inner in "$entry"/* "$entry"/.[!.]* "$entry"/..?*; do
                    [ -e "$inner" ] || [ -L "$inner" ] || continue # an unmatched glob
                    [ "${inner##*/}" = .staging ] \
                        || refuse "$RUN_ROOT holds periods/${inner##*/} but no journal.jsonl: it is neither empty nor an estate to resume; inspect it"
                done
                ;;
            *) refuse "$RUN_ROOT holds ${entry##*/} but no journal.jsonl: it is neither empty nor an estate to resume; inspect it" ;;
        esac
    done
    genesis
}

# A genesis creates the anchor. An anchor that already exists belongs to a
# lineage, and a genesis against it would write a foreign sentinel into the
# root before dsl41 refuses it, which then blocks the roll's retry. This is
# the restart after an opener died before its sentinel, with the one-shot
# trigger already gone: refuse, and name the trigger.
genesis() {
    if [ -e "$ESTATE_ANCHOR" ] && { [ ! -r "$ESTATE_ANCHOR" ] || [ ! -x "$ESTATE_ANCHOR" ]; }; then
        refuse "$ESTATE_ANCHOR is not readable and searchable by $(id -un): cannot tell a genesis from a lineage"
    fi
    if [ -e "$ESTATE_ANCHOR/anchor.json" ]; then
        refuse "$ESTATE_ANCHOR holds a lineage and $RUN_ROOT holds no journal.jsonl: a genesis would fork it. To open $RUN_ROOT from that lineage, create $OPEN_TRIGGER and start again"
    fi
    echo genesis
}

# run_options' deployment half, as a seal's --next-* options (see run_options).
# Every other option is one the seal states itself; an option outside both
# lists refuses, because a seal would drop it and the opener would refuse
# the committed period (DL-407).
# shellcheck disable=SC2120  # its words are run_options', set inside
next_profile() {
    eval "set -- $(run_options)"
    sep=
    while [ $# -gt 0 ]; do
        case $1 in
            --detached)
                printf '%s--next-detached' "$sep"
                sep=' '
                ;;
            --deadman | --as-machine | --machine-policy)
                printf '%s--next-%s %s' "$sep" "${1#--}" "$(quote "$2")"
                sep=' '
                shift
                ;;
            -p | --run-root | --estate-anchor | --supervisor | --access-map) shift ;;
            *) refuse "run_options names $1, which no seal restates: add it to next_profile" ;;
        esac
        shift
    done
}

supervisor_command() {
    quote_all "$DSL41" supervise start --run-root "$RUN_ROOT"
}

# POSIX sh has one array, "$@", and a function cannot return it. Each
# command is therefore built as one shell-quoted line and re-split with
# `eval set --` below. The quoting leaves a word bare only when it holds
# nothing but characters Python's shlex.quote also leaves bare.
quote() {
    case $1 in
        '' | *[!A-Za-z0-9@%+=:,./_-]*)
            printf "'%s'" "$(printf '%s\n' "$1" | sed "s/'/'\\\\''/g")"
            ;;
        *) printf '%s' "$1" ;;
    esac
}

quote_all() {
    sep=
    for word in "$@"; do
        printf '%s' "$sep"
        quote "$word"
        sep=' '
    done
}

refuse() {
    printf 'dsl41-launch: %s\n' "$1" >&2
    exit 2
}

usage() {
    refuse "usage: dsl41-launch [--print] [engine|supervisor|supervisor-ready|supervisor-stop]\
 | dsl41-launch vars"
}

print=0
if [ "${1-}" = --print ]; then
    print=1
    shift
fi
[ $# -le 1 ] || usage
mode=${1-engine}

case $mode in
    engine) line=$(engine_command) || exit $? ;;
    supervisor) line=$(supervisor_command) || exit $? ;;
    supervisor-ready)
        [ "$print" -eq 0 ] || usage
        [ -x "$DSL41" ] || refuse "$DSL41 is not executable"
        # a real LIST answer, not a socket file (deployment-runbook ss3)
        for attempt in 1 2 3 4 5 6 7 8 9 10; do
            if "$DSL41" supervise list --run-root "$RUN_ROOT" >/dev/null 2>&1; then
                exit 0
            fi
            sleep 1
        done
        printf 'dsl41-launch: no supervisor answered on %s after %s tries\n' \
            "$RUN_ROOT" "$attempt" >&2
        exit 1
        ;;
    supervisor-stop)
        [ "$print" -eq 0 ] || usage
        # The unit's ExecStop. KillMode=control-group sends a stop's SIGTERM to every
        # process in the unit, the commands included; this sends it to the supervisor
        # alone and waits while it drains and stops its runs, so systemd's SIGTERM
        # reaches only what is left (DL-416). systemd runs it after the supervisor
        # exited on its own too; then MAINPID is empty or gone, and nothing is sent.
        [ -n "${MAINPID-}" ] || exit 0
        kill -TERM "$MAINPID" 2>/dev/null || exit 0
        while kill -0 "$MAINPID" 2>/dev/null; do
            sleep 0.2
        done
        exit 0
        ;;
    vars)
        [ "$print" -eq 0 ] || usage
        profile=$(next_profile) || exit $?
        for pair in "DSL41=$DSL41" "RUN_ROOT=$RUN_ROOT" "ESTATE_ANCHOR=$ESTATE_ANCHOR" \
            "ESTATE_RELEASES=$ESTATE_RELEASES" "ACTIVE=$ACTIVE" "ENVIRONMENT=$ENVIRONMENT" \
            "PROPERTIES=$PROPERTIES" "MAX_JOBS=$MAX_JOBS" "MAX_GRACE_S=$MAX_GRACE_S" \
            "SERVICE_ACCOUNT=$SERVICE_ACCOUNT" "ENGINE_UNIT=$ENGINE_UNIT"; do
            printf '%s=%s\n' "${pair%%=*}" "$(quote "${pair#*=}")"
        done
        printf 'NEXT_PROFILE=%s\n' "$(quote "$profile")"
        exit 0
        ;;
    *) usage ;;
esac

if [ "$print" -eq 1 ]; then
    printf '%s\n' "$line"
    exit 0
fi
[ -x "$DSL41" ] || refuse "$DSL41 is not executable"
# one shot: the trigger is gone before dsl41 runs, so no later start opens
case $line in
    *" --open-from "*)
        rm -f "$OPEN_TRIGGER" || refuse "cannot remove $OPEN_TRIGGER: not opening twice"
        ;;
esac
# one line in the service log names the command this start ran
printf 'dsl41-launch: %s: %s\n' "$mode" "$line" >&2
eval "set -- $line"
exec "$@"
