#!/bin/bash -p
# SPDX-License-Identifier: Apache-2.0
# The privileged collector observes system policy and publishes a bounded,
# sanitized cache. The kernel enforces timed firewall deadlines independently;
# this collector only reconciles their private metadata through the same
# operation lock as interactive use. It never reapplies native firewall policy.
set -Eeuo pipefail
umask 077
IFS=$' \t\n'
PATH=/usr/sbin:/usr/bin:/sbin:/bin
export PATH
unset BASH_ENV ENV CDPATH DOCKER_HOST DOCKER_CONTEXT DOCKER_CONFIG
((EUID == 0)) || {
    printf 'The status collector requires root.\n' >&2
    exit 1
}
STATUS_SELF=$(/usr/bin/readlink -f -- "${BASH_SOURCE[0]}") || exit 1
readonly STATUS_SELF
readonly OCTOSHIELD_ROOT=${STATUS_SELF%/src/status-daemon}
for status_module in core controls usb monitor office profiles profile_firewall_verify profile_controls status access connections diagnostics repair; do
    # shellcheck source=/dev/null
    source "$OCTOSHIELD_ROOT/src/lib/$status_module.sh"
done
unset status_module

# Keep the supervised shell alive until timeout's KILL grace expires. Otherwise
# a TERM-resistant descendant could outlive a shell that exits immediately and
# retain its inherited read lock after timeout stops supervising the group.
# shellcheck disable=SC2317,SC2329
status_daemon::interrupted() {
    trap '' TERM
    while :; do sleep 1; done
}

status_daemon::after_change() {
    local mode=$1 gate="$CORE_STATE/lock-admission" lock="$CORE_STATE/lock" actual expected descriptor
    core::package_available || return 1
    core::private_directory "$CORE_STATE" && core::safe_lock "$gate" && core::safe_lock "$lock" || return 1
    for descriptor in 6 9; do
        if [[ $descriptor == 6 ]]; then expected=$gate; else expected=$lock; fi
        actual=$(stat -Lc '%d:%i' -- "/dev/fd/$descriptor") || return 1
        [[ $actual == "$(stat -c '%d:%i' -- "$expected")" ]] || return 1
        # An inherited lock's open description is already exclusive, so this
        # cannot block or unlock the parent. Unrelated descriptors fail closed.
        flock --exclusive --nonblock "$descriptor" || return 1
    done
    if [[ $mode == usb ]]; then status::refresh_usb; else status::refresh; fi
}

status_daemon::once() (
    local mode=${1:-full} result=0
    # The maintenance marker covers dpkg file replacement, while the shared
    # flock prevents reporting the middle of an interactive profile switch.
    if [[ $mode == inspect ]]; then
        core::package_available || return 1
    else
        core::package_available >/dev/null 2>&1 || return 0
    fi
    if [[ $mode == full ]] && declare -F profiles::expiry_due >/dev/null && profiles::expiry_due; then
        (
            core::try_begin 'Reconcile expired firewall exception metadata' || exit "$?"
            profiles::expire
        ) || result=$?
        if ((result != 0 && result != 75)); then
            printf 'OctoShield: firewall expiry metadata reconciliation failed; review the active profile. Kernel-enforced deadlines remain independent of this collector.\n' >&2
        fi
    fi
    result=0
    core::read_begin || result=$?
    if ((result != 0)); then
        if ((result == 75)) && [[ $mode != inspect ]]; then return 0; fi
        return "$result"
    fi
    if [[ $mode == usb ]]; then status::refresh_usb; else status::refresh; fi
)

case "${1:-}" in
    --details)
        shift
        case "${1-}:${2-}" in
            access:list) access::validate "${@:2}" || exit 2 ;;
            connections:list) connections::validate "${@:2}" || exit 2 ;;
            diagnostics:show) diagnostics::validate "${@:2}" || exit 2 ;;
            *) exit 2 ;;
        esac
        trap 'status_daemon::interrupted' TERM
        core::read_begin || exit "$?"
        "${1}::dispatch" "${@:2}"
        ;;
    --usb-once)
        [[ $# -eq 1 ]] || exit 2
        trap 'status_daemon::interrupted' TERM
        status_daemon::once usb
        ;;
    --once)
        [[ $# -eq 1 ]] || exit 2
        trap 'status_daemon::interrupted' TERM
        status_daemon::once
        ;;
    --inspect)
        [[ $# -eq 1 ]] || exit 2
        trap 'status_daemon::interrupted' TERM
        # Explicit inspection is read-only: expiry metadata reconciliation is
        # reserved for the background pass. Its caller supplies the deadline.
        status_daemon::once inspect
        ;;
    --after-change)
        [[ $# -eq 2 && ($2 == full || $2 == usb) ]] || exit 2
        trap 'status_daemon::interrupted' TERM
        status_daemon::after_change "$2"
        ;;
    '')
        [[ $# -eq 0 ]] || exit 2
        # USB has its own short-lived snapshot. Slow firewall verification must
        # not delay a device decision or make old firewall observations fresh.
        (
            while :; do
                core::timeout --kill-after=1s 8s /bin/bash -p "$STATUS_SELF" --usb-once || printf 'OctoShield: USB status refresh unavailable.\n' >&2
                sleep 2
            done
        ) &
        status_usb_pid=$!
        trap 'kill "$status_usb_pid" 2>/dev/null || :' EXIT
        trap 'exit 0' TERM INT HUP
        while :; do
            # A maximum-size firewall can require two complete verifications
            # when expiry bookkeeping is due. The 60-second bound plus this
            # loop's 15-second pause stays within the 90-second cache lifetime.
            core::timeout --kill-after=3s 60s /bin/bash -p "$STATUS_SELF" --once || printf 'OctoShield: live status refresh failed; the previous cache will become stale.\n' >&2
            sleep 15
        done
        ;;
    *)
        printf 'Usage: status-daemon [--once|--usb-once|--inspect|--after-change full|usb]\n' >&2
        exit 2
        ;;
esac
