#!/bin/sh
#
# nd-ha-remote - forced command of the "ndha" account (nd-ha-sshd, TCP 2225).
#
# Runs as the unprivileged ndha user for the peer node. The peer can only:
#   state      read this node's HA state (/run/nd-ha/state)
#   manifest   read the hash of the last configuration applied here
#   push       hand over a configuration bundle (stdin). It is queued in the
#              spool; a root service validates and applies it and the result
#              line is returned.
# Nothing else; no shell, no arguments.

umask 077

ROOT="${ND_HA_ROOT:-}"
STATE="$ROOT/run/nd-ha/state"
APPLIED="$ROOT/data/nd/ha/sync/applied"
SPOOL="$ROOT/data/nd/ha/spool"
RESULTS="$ROOT/run/nd-ha/sync-results"
MAX_BYTES=134217728        # 128 MB
WAIT_SECS=300

case "${SSH_ORIGINAL_COMMAND:-}" in
    state)
        if [ -r "$STATE" ]; then
            cat "$STATE"
        else
            echo "VRRP=NONE"
            echo "FORWARDING=0"
        fi
        ;;
    manifest)
        m=$(sed -n 's/^MANIFEST=//p' "$APPLIED" 2>/dev/null | head -n1)
        echo "${m:-none}"
        ;;
    push)
        id=$(tr -d '-' < /proc/sys/kernel/random/uuid 2>/dev/null)
        case "$id" in
            ''|*[!0-9a-f]*) echo "ERROR no request id"; exit 1 ;;
        esac
        n=0
        for f in "$SPOOL"/req-*.bundle; do
            [ -e "$f" ] && n=$((n + 1))
        done
        if [ "$n" -ge 3 ]; then
            echo "REFUSED busy ($n bundles waiting)"
            exit 1
        fi
        tmp="$SPOOL/.in-$id"
        if ! head -c $((MAX_BYTES + 1)) > "$tmp"; then
            rm -f "$tmp"
            echo "ERROR receive failed"
            exit 1
        fi
        size=$(wc -c < "$tmp")
        if [ "$size" -gt "$MAX_BYTES" ]; then
            rm -f "$tmp"
            echo "REFUSED bundle larger than $MAX_BYTES bytes"
            exit 1
        fi
        if [ "$size" -eq 0 ]; then
            rm -f "$tmp"
            echo "REFUSED empty bundle"
            exit 1
        fi
        mv -f "$tmp" "$SPOOL/req-$id.bundle" || { echo "ERROR spool"; exit 1; }
        i=0
        while [ "$i" -lt "$WAIT_SECS" ]; do
            r=$(grep "^$id " "$RESULTS" 2>/dev/null | tail -n1)
            if [ -n "$r" ]; then
                echo "${r#* }"
                case "$r" in "$id OK"*) exit 0 ;; esac
                exit 1
            fi
            sleep 1
            i=$((i + 1))
        done
        echo "ERROR no result after $WAIT_SECS s"
        exit 1
        ;;
    *)
        echo "ERROR unsupported command"
        exit 1
        ;;
esac
exit 0
