#!/bin/sh
# diagnostic: the state of the box for DEERA's support, run from the admin of the portal by deera-updater (root).
# A summary first, then the detail: system, a DEERA image and its two systems, packages, DEERA services, network and
# its configuration, reachability of the portal, the gateway and the repository, hardware, failed services, the last
# logs and those of the previous start.
# It only reads, and never prints a secret: the password of the gateway, the access of deera-ops, the password of the
# web interface and the Wi-Fi keys stay out, and the secret values of the configuration files it shows are masked.
set -u
export LC_ALL=C.UTF-8

started=$(date +%s)
conf=/etc/deera/agent.conf

has() { command -v "$1" >/dev/null 2>&1; }

title() {
    printf '\n%s\n' "$1"
    printf '%s\n' "$1" | sed 's/./=/g'
}

sub() { printf '\n-- %s\n' "$1"; }

value() { printf '%s: %s\n' "$1" "${2:--}"; }

# run COMMAND...: the command bounded in time, with its errors; nothing when the box does not have it
run() {
    has "$1" || return 0
    timeout 20 "$@" 2>&1
}

# setting KEY: a value of the agent's settings (the password of the gateway is never asked)
setting() { sed -n "s/^$1=//p" "$conf" 2>/dev/null | head -n 1 | tr -d '"'; }

# masked FILE...: the files without their comments and blank lines, the values of secret-looking settings masked
masked() {
    for file in "$@"; do
        [ -f "$file" ] && [ -r "$file" ] || continue
        printf -- '--- %s\n' "$file"
        awk '
            /^[[:space:]]*([#;]|$)/ { next }
            {
                l = tolower($0)
                if (l ~ /(pass|psk|secret|token|auth|private|credential|key)/) {
                    if (match($0, /[=:][[:space:]]*/)) { print substr($0, 1, RSTART + RLENGTH - 1) "********"; next }
                    if (match($0, /^[[:space:]]*[^[:space:]]+/)) { print substr($0, 1, RLENGTH) " ********"; next }
                }
                print
            }' "$file"
    done
}

# http URL: how a request goes (status, time, address), or why it fails
http() {
    has curl || { echo "curl absent"; return 0; }
    curl -sS -o /dev/null -m 10 -w 'HTTP %{http_code} in %{time_total}s (%{remote_ip})\n' "$1" 2>&1 | tr '\n' ' '
    echo
}

http_code() { has curl && curl -s -o /dev/null -m 10 -w '%{http_code}' "$1" 2>/dev/null; }

# tcp HOST PORT: whether a TCP connection opens
tcp() { timeout 8 bash -c ': </dev/tcp/$0/$1' "$1" "$2" >/dev/null 2>&1; }

mark() {
    case $1 in
        ok) printf '  [OK] %s: %s\n' "$2" "$3" ;;
        ko) printf '  [!!] %s: %s\n' "$2" "$3" ;;
        *) printf '  [--] %s: %s\n' "$2" "$3" ;;
    esac
}

portal=$(setting PORTAL_URL)
gateway=$(setting GATEWAY_SERVER)
channel=$(setting CHANNEL)
repo=$(grep -rhoE 'https?://[^[:space:]]*deera[^[:space:]]*' /etc/apt/sources.list.d/ 2>/dev/null | head -n 1)
container=$(systemd-detect-virt --container 2>/dev/null || true)
default_gw=$(ip -4 route show default 2>/dev/null | awk '{ print $3; exit }')

# a DEERA image: its system read-only and updated as a whole (two systems, A and B), its settings on /data
image_env=/usr/lib/deera/image.env
image() { sed -n "s/^$1=//p" "$image_env" 2>/dev/null | head -n 1 | tr -d '"'; }
on_image=false
[ -r "$image_env" ] && on_image=true
slot=$(sed -n 's/.*rauc\.slot=\([AB]\).*/\1/p' /proc/cmdline)
previous=/data/log/previous-boot.log

# emmc: the wear each eMMC reports, as "NAME WORST EOL": WORST is the worst of its two life_time estimates (1: 0 to 10 %
# of its life used, ... 10: 90 to 100 %, 11: exceeded), EOL its pre_eol_info (1: normal, 2: warning, 3: urgent)
emmc() {
    for card in /sys/bus/mmc/devices/*; do
        [ -r "$card/life_time" ] || continue
        set -- $(cat "$card/life_time")
        a=$(($1))
        b=$((${2:-0}))
        printf '%s %s %s\n' "$(cat "$card/name" 2>/dev/null)" "$((a > b ? a : b))" "$(($(cat "$card/pre_eol_info" 2>/dev/null || echo 0)))"
    done
}

# wear WORST: the life_time estimate in words
wear() {
    case $1 in
        0) echo "not reported" ;;
        11) echo "beyond its estimated life" ;;
        *) echo "$((($1 - 1) * 10)) to $(($1 * 10)) % of its life used" ;;
    esac
}

# blocked_loaded: the drivers an image keeps off (deera-*.conf) that are loaded all the same
blocked_loaded() {
    for module in $(sed -n 's/^\(install\|blacklist\) \([^ ]*\).*/\2/p' /etc/modprobe.d/deera-*.conf 2>/dev/null | sort -u); do
        grep -q "^$module " /proc/modules && printf ' %s' "$module"
    done
}

cat <<EOF
DEERA diagnostic
================
Generated on $(date '+%Y-%m-%d %H:%M:%S %Z') on $(hostname).
No secrets: the gateway password, the deera-ops access, the web interface password and the Wi-Fi keys are left out,
and the secret values of the configuration files are masked (********).
EOF

# ---------------------------------------------------------------------------------------------------------------------
title "Summary"

if systemctl is-active --quiet deera-agent; then
    if ss -tnp state established 2>/dev/null | grep -q '"deera-agent"'; then
        mark ok "Agent" "active, connected to the gateway"
    else
        mark ko "Agent" "active, but not connected to the gateway"
    fi
else
    mark ko "Agent" "$(systemctl is-active deera-agent 2>/dev/null)"
fi

if [ -n "$gateway" ]; then
    if tcp "${gateway%:*}" "${gateway##*:}"; then mark ok "Gateway" "$gateway reachable"; else mark ko "Gateway" "$gateway unreachable"; fi
fi
if [ -n "$portal" ]; then
    code=$(http_code "$portal/api/v1/health")
    if [ "$code" = 200 ]; then mark ok "Portal" "$portal answers"; else mark ko "Portal" "$portal: HTTP ${code:-000}"; fi
fi
if [ -n "$repo" ] && [ -n "$channel" ]; then
    code=$(http_code "$repo/dists/$channel/Release")
    if [ "$code" = 200 ]; then mark ok "Repository" "$repo ($channel) answers"; else mark ko "Repository" "$repo ($channel): HTTP ${code:-000}"; fi
fi

if [ -n "$default_gw" ]; then
    if ping -c 2 -W 2 "$default_gw" >/dev/null 2>&1; then mark ok "Router" "$default_gw answers"; else mark ko "Router" "$default_gw does not answer ping"; fi
else
    mark ko "Router" "no default route"
fi
if getent hosts deera.cloud >/dev/null 2>&1; then mark ok "DNS" "resolves"; else mark ko "DNS" "deera.cloud does not resolve"; fi

if [ "$(timedatectl show -p NTPSynchronized --value 2>/dev/null)" = yes ]; then
    mark ok "Clock" "synchronized ($(date '+%H:%M:%S %Z'))"
else
    mark ko "Clock" "not synchronized ($(date '+%Y-%m-%d %H:%M:%S %Z')): certificates may be refused"
fi

used=$(df -P / 2>/dev/null | awk 'NR == 2 { sub("%", "", $5); print $5 }')
if [ "${used:-0}" -lt 90 ]; then mark ok "Disk" "${used:-?}% used on /"; else mark ko "Disk" "${used}% used on /"; fi
available=$(awk '/^MemAvailable/ { printf "%d", $2 / 1024 }' /proc/meminfo)
total=$(awk '/^MemTotal/ { printf "%d", $2 / 1024 }' /proc/meminfo)
if [ "$available" -ge $((total / 10)) ]; then mark ok "Memory" "$available MB available of $total"; else mark ko "Memory" "$available MB available of $total"; fi
if $on_image; then
    if findmnt -n -o OPTIONS /data 2>/dev/null | grep -q '^rw'; then
        mark ok "File system" "/ read-only as on an image, the settings on /data"
    else
        mark ko "File system" "/data is not mounted read-write: the settings of the box are not kept"
    fi
elif grep -q ' / [^ ]* ro[ ,]' /proc/mounts 2>/dev/null; then
    mark ko "File system" "/ is read-only"
fi

failed=$(systemctl --failed --no-legend --plain 2>/dev/null | wc -l)
if [ "$failed" -eq 0 ]; then mark ok "Services" "none failed"; else mark ko "Services" "$failed failed (detail below)"; fi
if $on_image; then
    detail="$(image IMAGE_MODEL) $(image IMAGE_VERSION), system ${slot:-?}"
    if run rauc status | grep -q 'boot status: bad'; then
        mark ko "Image" "$detail; a system is marked bad (an update that did not start)"
    else
        mark ok "Image" "$detail"
    fi
    loaded=$(blocked_loaded)
    if [ -z "$loaded" ]; then mark ok "Drivers" "none of the blocked ones loaded"; else mark ko "Drivers" "blocked but loaded:$loaded"; fi
    ipv6=$(ip -6 -o address 2>/dev/null | wc -l)
    if [ "$ipv6" -eq 0 ]; then mark ok "IPv6" "off, IPv4 only"; else mark ko "IPv6" "$ipv6 address(es): a network file that leaves it on?"; fi
else
    upgradable=$(apt list --upgradable 2>/dev/null | grep -c /)
    mark info "System updates" "$upgradable pending"
fi
emmc | while read -r name worst eol; do
    if [ "$worst" -ge 9 ] || [ "$eol" -ge 2 ]; then
        mark ko "eMMC" "$name: $(wear "$worst"), end of life $([ "$eol" -ge 3 ] && echo urgent || echo near)"
    else
        mark ok "eMMC" "$name: $(wear "$worst")"
    fi
done
if [ -e /dev/watchdog0 ]; then
    watchdog=$(systemctl show -p RuntimeWatchdogUSec --value 2>/dev/null)
    case $watchdog in
        "" | 0 | infinity) mark info "Watchdog" "present, not armed" ;;
        *) mark ok "Watchdog" "armed by systemd ($watchdog): a box that freezes restarts" ;;
    esac
fi
if [ -r "$previous" ]; then
    last=$(tail -n 1 "$previous" | cut -d ' ' -f 1)
    mark info "Previous start" "its journal kept up to ${last%%.*} (at the end, with how it ended)"
fi

# ---------------------------------------------------------------------------------------------------------------------
title "System"

if [ -r /proc/device-tree/model ]; then
    value "Hardware" "$(tr -d '\0' </proc/device-tree/model)"
elif [ -r /sys/class/dmi/id/product_name ]; then
    value "Hardware" "$(cat /sys/class/dmi/id/sys_vendor 2>/dev/null) $(cat /sys/class/dmi/id/product_name 2>/dev/null)"
fi
value "Virtualization" "$(systemd-detect-virt 2>/dev/null)"
value "OS" "$(. /etc/os-release 2>/dev/null && echo "$PRETTY_NAME")"
value "Kernel" "$(uname -srvm)"
value "Architecture" "$(dpkg --print-architecture 2>/dev/null)"
value "CPU" "$(awk -F': ' '/^(model name|Model|Hardware)/ { print $2; exit }' /proc/cpuinfo), $(nproc) core(s)"
value "Up since" "$(uptime -s 2>/dev/null) ($(uptime -p 2>/dev/null))"
value "Load average" "$(cut -d ' ' -f 1-3 /proc/loadavg)"
for zone in /sys/class/thermal/thermal_zone*/temp; do
    [ -r "$zone" ] && value "Temperature" "$(awk '{ printf "%.1f °C", $1 / 1000 }' "$zone")" && break
done
if [ -n "$(image STATUS_LED)" ]; then
    value "Real-time clock" "no battery on the board: the time comes from the network"
fi
if has vcgencmd; then
    value "Power (get_throttled)" "$(vcgencmd get_throttled 2>&1) (0x0: never under-voltage nor throttled)"
fi

sub "Clock"
run timedatectl

sub "Memory"
run free -h

sub "Disks"
run df -hT -x tmpfs -x devtmpfs -x squashfs -x efivarfs
run df -hi /
value "Mount of /" "$(findmnt -n -o SOURCE,FSTYPE,OPTIONS / 2>/dev/null)"
if [ -z "$container" ]; then
    run lsblk -o NAME,SIZE,TYPE,FSTYPE,MOUNTPOINTS,MODEL
fi

# ---------------------------------------------------------------------------------------------------------------------
if $on_image; then
    title "Image"

    value "Model" "$(image IMAGE_MODEL)"
    value "Target" "$(image IMAGE_TARGET)"
    value "Version" "$(image IMAGE_VERSION)"
    value "Built for the channel" "$(image IMAGE_CHANNEL)"
    value "Running system" "${slot:-?}"
    value "Update in progress" "$(cat /var/lib/deera-image/pending 2>/dev/null)"

    sub "Systems (RAUC)"
    run rauc status --detailed | sed "s/$(printf '\033')\[[0-9;]*m//g"
    if has fw_printenv; then
        sub "Boot attempts (U-Boot)"
        run fw_printenv BOOT_ORDER BOOT_A_LEFT BOOT_B_LEFT
    fi
    for grubenv in /boot/firmware/EFI/deera/grubenv /boot/efi/EFI/deera/grubenv; do
        [ -r "$grubenv" ] || continue
        sub "Boot attempts (GRUB)"
        grep -E '^(ORDER|A_OK|B_OK|A_TRY|B_TRY)=' "$grubenv"
        break
    done
fi

# ---------------------------------------------------------------------------------------------------------------------
title "Packages"

sub "DEERA"
dpkg-query -W -f='${Package} ${Version} (${db:Status-Abbrev})\n' 'deera-*' 2>/dev/null
if ! $on_image; then
    grep -rh deera /etc/apt/sources.list /etc/apt/sources.list.d/ 2>/dev/null | grep -v '^#'
    run apt-cache policy deera-agent deera-webui
fi

sub "System and network"
dpkg-query -W -f='${db:Status-Abbrev} ${Package} ${Version}\n' systemd udev openssh-server sudo libpam-modules \
    ifupdown ifupdown2 isc-dhcp-client dhcpcd dhcpcd-base network-manager netplan.io systemd-resolved resolvconf \
    wpasupplicant hostapd iw nftables iptables ca-certificates openssl curl 'linux-image-*' raspberrypi-kernel \
    raspi-firmware 2>/dev/null | awk '$1 ~ /^ii/ { print $2, $3 }'

# an image never changes its packages: it is updated as a whole
if ! $on_image; then
    sub "Apt"
    value "Package lists updated on" "$(date -r /var/lib/apt/lists '+%Y-%m-%d %H:%M' 2>/dev/null)"
    value "Held packages" "$(apt-mark showhold 2>/dev/null | tr '\n' ' ')"
    audit=$(dpkg --audit 2>&1)
    value "Broken packages" "${audit:-none}"

    sub "Pending updates (first 30)"
    apt list --upgradable 2>/dev/null | grep / | head -n 30
fi

# ---------------------------------------------------------------------------------------------------------------------
title "DEERA agent"

value "Public id" "$(setting PUBLIC_ID)"
value "Serial number" "$(setting SERIAL)"
value "Model" "$(setting MODEL)"
value "Channel" "${channel:-set in the portal}"
value "Portal" "$portal"
value "Gateway" "$gateway"
value "Gateway fingerprint" "$(setting GATEWAY_FINGERPRINT)"

sub "Service"
systemctl status deera-agent --no-pager -n 0 2>&1 | head -n 12
value "Restarts" "$(systemctl show deera-agent -p NRestarts --value 2>/dev/null)"

sub "Connections"
ss -tnp state established 2>/dev/null | grep '"deera-agent"'

sub "Configuration"
masked /etc/deera-agent/deera-agent.conf

sub "Updater"
run systemctl list-timers deera-updater.timer --no-pager | head -n 2
if ! $on_image; then
    value "Versions kept for rollback" "$(ls /var/lib/deera-updater/packages 2>/dev/null | tr '\n' ' ')"
fi
value "Scripts available" "$(ls /usr/lib/deera/scripts 2>/dev/null | tr '\n' ' ')"

sub "deera-ops access"
value "Account" "$(getent passwd deera-ops >/dev/null && echo present || echo missing)"
value "Fleet password" "$([ -s /etc/deera/ops.conf ] && echo configured || echo 'not configured')"
value "PAM files" "$(grep -l deera-ops-auth /etc/pam.d/* 2>/dev/null | tr '\n' ' ')"
if has sshd; then
    sshd -T 2>/dev/null | grep -E '^(port|listenaddress|permitrootlogin|passwordauthentication|kbdinteractiveauthentication|usepam|allowusers|denyusers) '
fi

# ---------------------------------------------------------------------------------------------------------------------
title "Local web interface"

if systemctl cat deera-webui >/dev/null 2>&1; then
    systemctl status deera-webui --no-pager -n 0 2>&1 | head -n 8
    sub "Listening"
    ss -tlnp 2>/dev/null | grep '"deera-webui"'
    value "Password" "$([ -s /etc/deera/webui.conf ] && echo set || echo 'not set yet')"
else
    echo "Not installed."
fi

# ---------------------------------------------------------------------------------------------------------------------
title "Network"

value "Host name" "$(hostname -f 2>/dev/null || hostname)"

sub "Interfaces"
ip -brief link 2>/dev/null
echo
ip address 2>/dev/null

sub "Links"
for path in /sys/class/net/*; do
    iface=${path##*/}
    [ -d "$path" ] && [ "$iface" != lo ] || continue
    driver=$(basename "$(readlink -f "$path/device/driver" 2>/dev/null)" 2>/dev/null)
    printf '%s: state %s, carrier %s, %s Mb/s %s, MTU %s%s\n' "$iface" \
        "$(cat "$path/operstate" 2>/dev/null)" "$(cat "$path/carrier" 2>/dev/null || echo ?)" \
        "$(cat "$path/speed" 2>/dev/null || echo ?)" "$(cat "$path/duplex" 2>/dev/null)" \
        "$(cat "$path/mtu" 2>/dev/null)" "${driver:+, driver $driver}"
done

sub "Routes"
ip route 2>/dev/null
ip -6 route 2>/dev/null | grep -v '^fe80\|^multicast\|^anycast'

sub "Neighbours"
ip neigh 2>/dev/null

sub "DNS"
masked /etc/resolv.conf
if systemctl is-active --quiet systemd-resolved; then
    run resolvectl status --no-pager | head -n 30
fi

sub "Network management"
for unit in systemd-networkd networking NetworkManager dhcpcd systemd-resolved wpa_supplicant hostapd; do
    state=$(systemctl is-active "$unit" 2>/dev/null)
    [ "$state" = inactive ] || [ -z "$state" ] || printf '%s: %s\n' "$unit" "$state"
done
if systemctl is-active --quiet systemd-networkd; then
    run networkctl list --no-pager
fi

sub "Configuration"
masked /etc/network/interfaces /etc/network/interfaces.d/* /etc/systemd/network/*.network /etc/systemd/network/*.link \
    /etc/systemd/network/*.netdev /etc/dhcpcd.conf /etc/netplan/*.yaml /etc/NetworkManager/system-connections/*

if ls -d /sys/class/net/*/wireless >/dev/null 2>&1; then
    sub "Wi-Fi"
    run iw dev
    run iw reg get | head -n 12
    run rfkill list
    for path in /sys/class/net/*/wireless; do
        iface=$(basename "$(dirname "$path")")
        has wpa_cli && timeout 5 wpa_cli -i "$iface" status 2>/dev/null | grep -v -i 'psk\|passphrase'
    done
fi

sub "Listening ports"
ss -tulnp 2>/dev/null

sub "Firewall"
if has nft; then
    rules=$(timeout 10 nft list ruleset 2>&1)
    if [ -n "$rules" ]; then printf '%s\n' "$rules" | head -n 80; else echo "nftables: no rules"; fi
fi
if has iptables-save; then
    iptables-save 2>/dev/null | grep -v '^#' | head -n 60
fi

# ---------------------------------------------------------------------------------------------------------------------
title "Reachability"

if [ -n "$default_gw" ]; then
    sub "Router ($default_gw)"
    ping -c 3 -W 2 "$default_gw" 2>&1 | tail -n 2
fi
sub "Internet (1.1.1.1, 9.9.9.9)"
ping -c 3 -W 2 1.1.1.1 2>&1 | tail -n 2
ping -c 3 -W 2 9.9.9.9 2>&1 | tail -n 2
value "1500-byte packets without fragmentation" \
    "$(ping -c 1 -W 3 -M do -s 1472 1.1.1.1 >/dev/null 2>&1 && echo pass || echo 'do not pass (smaller MTU on the path)')"

sub "DNS resolution"
for host in "${portal#*://}" "${gateway%:*}" "$(printf '%s' "$repo" | sed 's|^[a-z]*://||; s|/.*||')" deera.cloud; do
    host=${host%%/*}
    [ -n "$host" ] || continue
    addresses=$(timeout 10 getent ahosts "$host" 2>/dev/null | awk '{ print $1 }' | sort -u | tr '\n' ' ')
    value "$host" "${addresses:-no answer}"
done

sub "DEERA services"
[ -n "$portal" ] && value "Portal" "$(http "$portal/api/v1/health")"
if [ -n "$gateway" ]; then
    value "Gateway (TCP)" "$(tcp "${gateway%:*}" "${gateway##*:}" && echo "$gateway reachable" || echo "$gateway unreachable")"
fi
[ -n "$repo" ] && [ -n "$channel" ] && value "Repository" "$(http "$repo/dists/$channel/Release")"

# ---------------------------------------------------------------------------------------------------------------------
title "Hardware"

sub "USB"
if has lsusb; then
    lsusb
else
    for dev in /sys/bus/usb/devices/*; do
        [ -r "$dev/idVendor" ] || continue
        printf '%s:%s %s %s\n' "$(cat "$dev/idVendor")" "$(cat "$dev/idProduct")" \
            "$(cat "$dev/manufacturer" 2>/dev/null)" "$(cat "$dev/product" 2>/dev/null)"
    done
fi

sub "eMMC"
found=$(emmc)
if [ -n "$found" ]; then
    printf '%s\n' "$found" | while read -r name worst eol; do
        printf '%s: %s; end of life %s\n' "$name" "$(wear "$worst")" \
            "$(case $eol in 1) echo normal ;; 2) echo near ;; 3) echo urgent ;; *) echo "not reported" ;; esac)"
    done
else
    echo "None reporting its wear."
fi

sub "Watchdog"
if [ -e /dev/watchdog0 ]; then
    value "Device" "$(cat /sys/class/watchdog/watchdog0/identity 2>/dev/null)"
    value "Armed by systemd" "$(systemctl show -p RuntimeWatchdogUSec --value 2>/dev/null)"
else
    echo "None."
fi

if $on_image; then
    sub "Drivers kept off"
    loaded=$(blocked_loaded)
    value "Blocked but loaded" "${loaded:-none}"
fi

sub "Kernel messages (errors and warnings, last 25)"
if [ -n "$container" ] && [ "$container" != none ]; then
    echo "Not readable in a container ($container)."
else
    dmesg --level=emerg,alert,crit,err,warn -T 2>&1 | tail -n 25
fi

# ---------------------------------------------------------------------------------------------------------------------
title "Services"

sub "Failed"
systemctl --failed --no-legend --plain 2>/dev/null
[ "$failed" -eq 0 ] && echo "None."

sub "Last boots"
journalctl --list-boots --no-pager 2>/dev/null | tail -n 5
run systemd-analyze time

# ---------------------------------------------------------------------------------------------------------------------
title "Logs"

# routine lines: each start of the updater, the sudo sessions of the agent's package checks, the browsers that do not
# know the certificate of the web interface yet
routine='systemd\[1\]: (Starting|Finished) |\.service: (Deactivated successfully|Consumed )|pam_unix\(sudo:session\)|TLS handshake error'

# journal TITLE LINES OPTIONS...: the last lines of a log, without its routine lines
journal() {
    sub "$1"
    lines=$2
    shift 2
    journalctl "$@" -n 1000 --no-pager -o short-iso 2>/dev/null | grep -Ev "$routine" | tail -n "$lines" | cut -c 1-240
}

journal "Errors since boot (last 30)" 30 -p err -b
journal "Agent (last 50 lines)" 50 -u deera-agent
journal "Updater (last 30 lines)" 30 -u deera-updater
if systemctl cat deera-webui >/dev/null 2>&1; then
    journal "Web interface (last 20 lines)" 20 -u deera-webui
fi
journal "Network (last 20 lines)" 20 -u systemd-networkd -u networking -u NetworkManager -u dhcpcd -u 'ifup@*'
journal "deera-ops sign-ins (last 7 days)" 15 --since "-7 days" -t deera-ops-auth

# the journal stays in memory on an image: the end of the previous start is kept on /data as the box shuts down
if [ -r "$previous" ]; then
    # who asked: the updater (an update of the image, the portal), the web interface, the button, the check after an
    # update, a command; a power cut or a freeze leaves no journal, so this one is then of an earlier start
    sub "Previous start: how it ended"
    ended=$(grep -E 'systemd-logind\[[0-9]+\]: (The system will|System is) |deera-updater\[[0-9]+\]: .*restarting|deera-webui\[[0-9]+\]: (reboot|poweroff) asked|button held|not healthy|COMMAND=.*(reboot|poweroff|shutdown|halt)' "$previous" |
        tail -n 8 | cut -c 1-240)
    printf '%s\n' "${ended:-No restart asked in it: a power cut or a freeze leaves no journal, so it may be of an earlier start.}"
    sub "Previous start (last 40 lines)"
    grep -Ev "$routine" "$previous" | tail -n 40 | cut -c 1-240
fi

printf '\nDiagnostic done in %ss.\n' "$(($(date +%s) - started))"
exit 0
