#!/pckg/option/bin/bash
# OLSR lease supervisor. Only protocol 100 in the reserved tables is removed.
set -eu
BB=/pckg/option/bin/busybox
BASE=/ram/olsr
SELF=/pckg/olsr/bin/olsrctl
CONFIG=/rw/disk/olsrd.conf
DAEMON=/pckg/olsr/bin/olsrd
RUN=/pckg/olsr/bin/run-child
BIRD=/pckg/olsr/bin/bird
LOGGER=/pckg/olsr/bin/log-ring
now() { read -r seconds rest < /proc/uptime; printf '%s\n' "${seconds%%.*}"; }
owned_routes() {
    for table in 201 202 203; do
        "$BB" ip route flush table "$table" proto 100 || true
    done
}
cleanup() {
    trap - EXIT INT TERM HUP
    # Withdraw native routes first by closing BGP, then stop OLSR.
    for pid in ${bird:-} ${child:-}; do
        "$BB" kill -TERM "$pid" 2>/dev/null || true
        remaining=xxx
        while "$BB" kill -0 "$pid" 2>/dev/null && [ -n "$remaining" ]; do
            "$BB" sleep 1
            remaining=${remaining%x}
        done
        "$BB" kill -KILL "$pid" 2>/dev/null || true
        wait "$pid" 2>/dev/null || true
    done
    for pid in ${loggers:-}; do wait "$pid" 2>/dev/null || true; done
    # Exact rule selector; do not disturb RouterOS rules or other protocols.
    "$BB" ip rule del to 10.0.0.0/8 lookup 201 priority 20010 2>/dev/null || true
    owned_routes
    "$BB" rm -f "$BASE/child.pid" "$BASE/supervisor.pid"
    "$BB" rm -rf "$BASE/lock"
}
prepare() {
    [ -s "$CONFIG" ] || { echo "Missing $CONFIG"; return 1; }
    # These values belong to the supervisor, not the editable configuration.
    if "$BB" grep -Eq '^[[:space:]]*(RtProto|RtTable[^[:space:]]*|SmartGateway|LoadPlugin|Hna4|Hna6)[[:space:]{]' "$CONFIG"; then
        echo 'Reserved routing, plugin, or advertisement setting in configuration'; return 1
    fi
    mainip=$("$BB" sed -n 's/^[[:space:]]*MainIp[[:space:]]\+\([0-9.]*\)[[:space:]]*$/\1/p' "$CONFIG")
    [ -n "$mainip" ] || { echo 'Set exactly one MainIp'; return 1; }
    "$BB" ip -o -4 address show > "$BASE/addresses"
    device=
    while read -r index name family address rest; do
        if [ "${address%/*}" = "$mainip" ]; then device=${name%%@*}; fi
    done < "$BASE/addresses"
    [ -n "$device" ] || { echo 'MainIp is not assigned to an interface'; return 1; }
    case "$device" in *[!a-zA-Z0-9_.:-]*) echo 'Unsupported Linux interface name'; return 1;; esac
    "$BB" sed "s/@INTERFACE@/$device/g" "$CONFIG" > "$BASE/active.conf"
    cat_config='\nRtProto 100\nRtTable 201\nRtTableDefault 202\nRtTableTunnel 203\nRtTablePriority none\nRtTableDefaultOlsrPriority none\nRtTableTunnelPriority none\nRtTableDefaultPriority none\nSmartGateway no\n'
    printf '%b' "$cat_config" >> "$BASE/active.conf"
}
"$BB" mkdir -p "$BASE"
case "${1:-status}" in
    pulse)
        now > "$BASE/lease.new"
        "$BB" mv "$BASE/lease.new" "$BASE/lease"
        if [ -f "$BASE/supervisor.pid" ]; then
            read -r supervisor < "$BASE/supervisor.pid"
            case "$supervisor" in ''|*[!0-9]*) exit 1;; esac
            if ! "$BB" kill -0 "$supervisor" 2>/dev/null; then
                "$BB" rm -rf "$BASE/lock"
            fi
        fi
        if "$BB" mkdir "$BASE/lock" 2>/dev/null; then
            # Ignore the invoking SSH/RouterOS session closing.
            /pckg/olsr/bin/start-service
        fi
        ;;
    supervise)
        child=
        bird=
        loggers=
        printf '%s\n' "$$" > "$BASE/supervisor.pid"
        trap cleanup EXIT INT TERM HUP
        prepare
        owned_routes
        "$BB" rm -f "$BASE/olsr.pipe" "$BASE/bird.pipe"
        "$BB" mkfifo "$BASE/olsr.pipe"
        "$LOGGER" "$BASE/olsr.log" < "$BASE/olsr.pipe" &
        loggers=$!
        "$RUN" "$DAEMON" -f "$BASE/active.conf" -nofork > "$BASE/olsr.pipe" 2>&1 &
        child=$!
        if [ -x "$BIRD" ]; then
            "$BB" sed "s/@MAINIP@/$mainip/g" /pckg/olsr/etc/bird.conf.template > "$BASE/bird.conf"
            "$BB" mkfifo "$BASE/bird.pipe"
            "$LOGGER" "$BASE/bird.log" < "$BASE/bird.pipe" &
            loggers="$loggers $!"
            "$RUN" "$BIRD" -f -c "$BASE/bird.conf" -s "$BASE/bird.sock" -P "$BASE/bird.pid" > "$BASE/bird.pipe" 2>&1 &
            bird=$!
        else
            "$BB" ip rule add to 10.0.0.0/8 lookup 201 priority 20010
        fi
        printf '%s\n' "$child" > "$BASE/child.pid"
        echo "Running on $device with MainIp $mainip; BGP bridge PID: ${bird:-disabled}"
        previous=
        missed=
        while "$BB" kill -0 "$child" 2>/dev/null; do
            if [ -n "$bird" ] && ! "$BB" kill -0 "$bird" 2>/dev/null; then break; fi
            lease=0
            [ ! -f "$BASE/lease" ] || read -r lease < "$BASE/lease"
            case "$lease" in ''|*[!0-9]*) break;; esac
            [ "$lease" != 0 ] || break
            if [ "$lease" = "$previous" ]; then missed="${missed}x"; else missed=; fi
            previous=$lease
            [ "$missed" != xxxxxxx ] || break
            # RouterOS Files is backed by tmpfs here on supported ARM devices.
            # The actual ring remains under /ram; a snapshot is exported on demand.
            "$BB" sleep 1
        done
        echo 'Stopped: daemon exited or enable lease expired'
        ;;
    stop)
        # Expire the lease. The supervisor owns process shutdown and cleanup.
        printf '0\n' > "$BASE/lease"
        ;;
    export-logs)
        # /rw/pckg is the RAM-backed Files root on the supported ARM layout.
        # Fail closed if the mount is not tmpfs, avoiding accidental flash logs.
        "$BB" grep -q ' /flash/rw/pckg tmpfs ' /proc/mounts || exit 1
        for name in olsr bird; do
            output=olsr-log.txt
            [ "$name" != bird ] || output=olsr-bird-log.txt
            [ ! -f "$BASE/$name.log" ] || "$BB" cp "$BASE/$name.log" "/rw/pckg/$output"
        done
        ;;
    logs)
        for name in olsr bird; do
            [ ! -f "$BASE/$name.log" ] || "$BB" cat "$BASE/$name.log"
        done
        ;;
    status)
        [ ! -f "$BASE/status" ] || "$BB" cat "$BASE/status"
        "$BB" ip route show table 201 proto 100
        ;;
    *) echo 'Usage: olsrctl pulse|stop|status|logs|export-logs' >&2; exit 2;;
esac
