#!/bin/sh
# Adaptive DS Client -- install-time system check. Informational only: logs to
# /var/lib/adaptive-ds/logs/install.log and ALWAYS exits 0 so it can never fail an install.
LOG="/var/lib/adaptive-ds/logs/install.log"
mkdir -p "$(dirname "$LOG")" 2>/dev/null || true

log() { { printf '%s system-check: %s\n' "$(date '+%Y-%m-%d %H:%M:%S %Z')" "$*" >> "$LOG"; } 2>/dev/null || true; }

run() {
    log "--- begin (package adaptive-ds-client) ---"

    if command -v timedatectl >/dev/null 2>&1; then
        tz="$(timedatectl show -p Timezone --value 2>/dev/null)"
        ntp="$(timedatectl show -p NTPSynchronized --value 2>/dev/null)"
        ntpsvc="$(timedatectl show -p NTP --value 2>/dev/null)"
        log "timezone=${tz:-unknown}"
        log "ntp_synchronized=${ntp:-unknown} ntp_service_enabled=${ntpsvc:-unknown}"
        [ "${ntp:-}" = "yes" ] || log "WARNING: clock is not NTP-synchronized; schedules and certificate checks can misbehave"
    else
        log "timedatectl not available; timezone/NTP state unknown"
    fi

    connected=0
    for st in /sys/class/drm/card*-*/status; do
        [ -e "$st" ] || continue
        if [ "$(cat "$st" 2>/dev/null)" = "connected" ]; then
            connected=$((connected + 1))
            log "drm output connected: $(basename "$(dirname "$st")")"
        fi
    done
    if [ "$connected" -gt 0 ]; then log "connected_drm_outputs=$connected"
    else log "WARNING: no connected DRM output found (headless, or install running over SSH/in a VM without a display)"; fi

    # Starting a real X server here would fight the running session for a VT, so check readiness only.
    if [ -x /usr/bin/Xorg ] || [ -x /usr/lib/xorg/Xorg ]; then
        xv="$(timeout 10 Xorg -version 2>&1 | grep -i 'X.Org X Server' | head -n 1)"
        log "xorg_present=yes version=${xv:-unknown}"
    else
        log "WARNING: Xorg binary not found"
    fi
    if ls /dev/dri/card* >/dev/null 2>&1; then log "dri_device_nodes=present"
    else log "WARNING: no /dev/dri/card* node; Xorg modesetting driver will not start on this machine"; fi
    # Web zones: WebKitGTK + PyGObject (informational; the .deb Depends pull them in).
    wk="$(dpkg-query -W -f='${Version}' libwebkit2gtk-4.1-0 2>/dev/null)"
    log "webkit2gtk_4_1=${wk:-not installed}"
    if command -v python3 >/dev/null 2>&1 && python3 -c 'import gi' >/dev/null 2>&1; then
        log "python3_gi=available"
    else
        log "WARNING: python3 gi (PyGObject) not importable; web-zone items will be skipped"
    fi
    id adsclient >/dev/null 2>&1 && log "kiosk_account=$(id adsclient 2>/dev/null)"

    log "--- end ---"
}

run || true
exit 0
