#!/bin/sh
# Starts the Jaw node (#61). When the node has staged a verified update (an owner pressed "Install now", or
# Jaw:Updates:Mode=auto), it writes the release's folder to $app/pending and stops; this script then switches to it.
# A new version is on trial until the health check sees it answering; if it stops before that, the next start goes
# back to the previous version. /opt/jaw (installed by hand) is always the last fallback.
set -u
data=${Jaw__DataDirectory:-/var/lib/jaw}
app=$data/app
fallback=/opt/jaw

usable() { [ -n "$1" ] && [ -f "$1/Jaw.Server.dll" ] && case "$1" in "$app"/releases/*) true ;; *) false ;; esac; }

if [ -f "$app/trial" ]; then
    # The last version started on trial and stopped before it was confirmed: roll back.
    echo "jaw-run: the new version stopped before it was confirmed; going back to the previous one"
    # Remember it, so the node doesn't install that release again.
    [ -f "$app/current" ] && basename "$(cat "$app/current")" >> "$app/failed"
    if [ -f "$app/previous" ] && usable "$(cat "$app/previous")"; then
        cp "$app/previous" "$app/current"
    else
        rm -f "$app/current"
    fi
    rm -f "$app/trial" "$app/pending"
fi

if [ -f "$app/pending" ]; then
    new=$(cat "$app/pending")
    rm -f "$app/pending"
    if usable "$new"; then
        if [ -f "$app/current" ]; then cp "$app/current" "$app/previous"; else rm -f "$app/previous"; fi
        echo "$new" > "$app/current"
        date +%s > "$app/trial"
        echo "jaw-run: switching to $new (on trial until the health check confirms it)"
    fi
fi

dir=$fallback
if [ -f "$app/current" ] && usable "$(cat "$app/current")"; then
    dir=$(cat "$app/current")
fi

# Keep only the current and previous releases.
if [ -d "$app/releases" ]; then
    keep_current=$(cat "$app/current" 2>/dev/null || true)
    keep_previous=$(cat "$app/previous" 2>/dev/null || true)
    for r in "$app"/releases/*; do
        [ -d "$r" ] || continue
        [ "$r" = "$keep_current" ] || [ "$r" = "$keep_previous" ] || rm -rf "$r"
    done
fi

export JAW_LAUNCHER=1
cd "$dir" || exit 1
exec /usr/bin/dotnet "$dir/Jaw.Server.dll"
