#!/bin/sh
# iemi-test: the CricketOne board self-test, steps 5-10 of test-procedure.md and the checks around them.
# Plain POSIX sh with busybox, i2c-tools, alsa-utils and v4l-utils: the tools in the module maker's Linux (RV1126B)
# and in Raspberry Pi OS, so the same script runs on the rev A-1 board and on the Pi Zero 2 W bench kit.
#
#   iemi-test [all|probe|system|chips|cameras|fps|lights|sound|speaker|mic|power|charger|sd|wifi|bt|bails|switches]
#             [--board a1|pi] [--auto]
#
#   system   4 cores, 2 GB memory, the eMMC, the AI engine, video encoder and camera drivers, the chip temperature
#   chips    every I2C part answers with its own identity: gauge, motion sensor, ID chip, security chip, camera, lights
#   cameras  30 frames, the picture not flat;   fps  10 s at full rate: 119 fps or more every second, no lost frame
#   lights   each light red, then green, then all red, green, amber;   sound  speaker, then microphone
#   wifi     scan and signal, access-point mode, 5 GHz, speed to a test server;   bt  the Bluetooth controller
#   charger  the LTC4162-F answers as a LiFePO4 part; with USB-C in: 1 cell, input 4.5 V or more, charging
#   bails, switches   the two bail sensors; the tamper switch and the power key
#
# The board profile (board-a1.env, board-pi.env, next to this script or in /etc/iemi) names the buses, nodes and
# lines; anything a profile leaves empty is SKIP, never FAIL. Every run appends to iemi-test.log and writes
# iemi-test-result.json (in $IEMI_OUT, default the current folder); the last line is PASS or FAIL.
# IEMI_SYSFS, IEMI_PROCFS and IEMI_DEVFS (default /sys, /proc and none) point the readings at a stand-in tree
# (standin/run-standin-test); with IEMI_DEVFS set, device nodes are looked for under it and need not be special files.
# --auto: no questions (the factory line): lights run their sequence and pass on the driver's answers,
# the microphone test listens to the speaker's tone instead of taps, switch lines pass when readable.
set -u
VERSION="2.3 (9 Nov 2026)"
HERE=$(cd "$(dirname "$0")" && pwd)
WHAT=all; BOARD=""; AUTO=0
while [ $# -gt 0 ]; do
  case "$1" in
    --board) BOARD="$2"; shift ;;
    --auto) AUTO=1 ;;
    -h|--help) sed -n '2,22p' "$0"; exit 0 ;;
    *) WHAT="$1" ;;
  esac; shift
done
if [ -z "$BOARD" ]; then
  if grep -qi "raspberry" /proc/device-tree/model 2>/dev/null; then BOARD=pi; else BOARD=a1; fi
fi
PROFILE=""
for p in "$HERE/board-$BOARD.env" "/etc/iemi/board-$BOARD.env"; do [ -f "$p" ] && PROFILE="$p" && break; done
[ -n "$PROFILE" ] || { echo "no board profile board-$BOARD.env"; exit 2; }
# shellcheck disable=SC1090
. "$PROFILE"
SYS=${IEMI_SYSFS:-/sys}; PROC=${IEMI_PROCFS:-/proc}; DEVFS=${IEMI_DEVFS:-}
OUT=${IEMI_OUT:-.}; LOG="$OUT/iemi-test.log"; JSON="$OUT/iemi-test-result.json"; TMP=${TMPDIR:-/tmp}/iemi-test.$$
mkdir -p "$TMP"; trap 'rm -rf "$TMP"' EXIT
RESULTS=""; NFAIL=0; NPASS=0; NSKIP=0

say() { echo "$*"; echo "$(date '+%F %T') $*" >> "$LOG"; }
result() {   # result <test> <PASS|FAIL|SKIP> <detail>
  say "$2  $1: $3"
  case "$2" in PASS) NPASS=$((NPASS+1)) ;; FAIL) NFAIL=$((NFAIL+1)) ;; *) NSKIP=$((NSKIP+1)) ;; esac
  d=$(printf '%s' "$3" | sed 's/\\/\\\\/g; s/"/\\"/g')
  RESULTS="$RESULTS${RESULTS:+,}{\"test\":\"$1\",\"result\":\"$2\",\"detail\":\"$d\"}"
}
have() { command -v "$1" >/dev/null 2>&1; }
ask() {      # ask <question>: yes returns 0; --auto answers yes
  [ "$AUTO" = 1 ] && return 0
  printf '%s [y/n] ' "$1"; read -r a; case "$a" in y|Y|yes) return 0 ;; *) return 1 ;; esac
}
i2c_has() {  # i2c_has <bus> <addr>: the device answers a read
  i2cget -y -f "$1" "$2" 0x00 >/dev/null 2>&1 || i2cget -y -f "$1" "$2" >/dev/null 2>&1   # -f: a bound driver must not read as absent
}
mux() {      # mux <channel|off>: the head's TCA9546A
  [ -n "${MUX_ADDR:-}" ] || return 0
  if [ "$1" = off ]; then i2cset -y "$CAM_BUS" "$MUX_ADDR" 0x00 2>/dev/null; else i2cset -y "$CAM_BUS" "$MUX_ADDR" $((1 << $1)) 2>/dev/null; fi
}

# ---------------------------------------------------------------- probe: what the board has
t_probe() {
  say "== probe: board $BOARD ($PROFILE), iemi-test $VERSION"
  say "model: $( { tr -d '\0' < /proc/device-tree/model; } 2>/dev/null || uname -m); kernel $(uname -r)"
  for t in i2cget i2cset aplay arecord v4l2-ctl; do have "$t" || say "missing tool: $t"; done
  if have v4l2-ctl; then v4l2-ctl --list-devices 2>/dev/null | sed 's/^/  /' | tee -a "$LOG" | head -40; fi
  have aplay && aplay -l 2>/dev/null | grep '^card' | sed 's/^/  play: /' | tee -a "$LOG"
  have arecord && arecord -l 2>/dev/null | grep '^card' | sed 's/^/  record: /' | tee -a "$LOG"
  have i2cdetect && for b in ${MAIN_BUS:-} ${CAM_BUS:-}; do say "  i2c bus $b:"; i2cdetect -y "$b" 2>/dev/null | sed 's/^/    /' | tee -a "$LOG"; done
  result probe PASS "inventory written to iemi-test.log"
}

# ---------------------------------------------------------------- system: processor, memory, storage, drivers, heat
t_system() {
  say "== system: processor, memory, eMMC, AI engine, video encoder, chip temperature"
  if [ -n "${SYS_CPUS:-}" ]; then
    n=$(grep -c '^processor' "$PROC/cpuinfo" 2>/dev/null); n=${n:-0}
    if [ "$n" -ge "$SYS_CPUS" ]; then result cpu PASS "$n cores"; else result cpu FAIL "$n cores, $SYS_CPUS expected"; fi
  fi
  if [ -n "${SYS_RAM_MB:-}" ]; then
    mb=$(awk '/MemTotal/ {printf "%d", $2 / 1024}' "$PROC/meminfo" 2>/dev/null); mb=${mb:-0}
    if [ "$mb" -ge "$SYS_RAM_MB" ]; then result memory PASS "$mb MB"; else result memory FAIL "$mb MB, $SYS_RAM_MB MB expected"; fi
  fi
  if [ -n "${EMMC_DEV:-}" ]; then
    if [ -b "$DEVFS$EMMC_DEV" ] || { [ -n "$DEVFS" ] && [ -e "$DEVFS$EMMC_DEV" ]; }; then
      gb=$(( $(cat "$SYS/class/block/${EMMC_DEV##*/}/size" 2>/dev/null || echo 0) / 1953125 ))
      result emmc PASS "$EMMC_DEV, about $gb GB"
    else result emmc FAIL "$EMMC_DEV missing (the module's eMMC)"; fi
  fi
  for pair in ${SYS_NODES:-}; do n=${pair%%=*}; d=${pair#*=}   # name=device node a driver makes
    if [ -e "$DEVFS$d" ]; then result "$n" PASS "$d present"; else result "$n" FAIL "$d missing: its driver is not loaded"; fi
  done
  t=0; for z in "$SYS"/class/thermal/thermal_zone*/temp; do [ -r "$z" ] || continue; v=$(cat "$z" 2>/dev/null); [ "${v:-0}" -gt "$t" ] && t=$v; done
  if [ "$t" -eq 0 ]; then result temperature SKIP "no thermal zone"
  elif [ $((t / 1000)) -le "${TEMP_MAX:-85}" ]; then result temperature PASS "hottest zone $((t / 1000)) C"
  else result temperature FAIL "hottest zone $((t / 1000)) C, over ${TEMP_MAX:-85} C"; fi
}

# ---------------------------------------------------------------- chips: every I2C part answers with its identity
t_chips() {
  say "== chips: each I2C part answers, and with its own identity where it has one"
  have i2cget || { result chips SKIP "i2c-tools not installed"; return; }
  if [ -n "${MAIN_BUS:-}" ]; then
    for pair in ${MAIN_I2C:-}; do n=${pair%%=*}; a=${pair#*=}
      if i2c_has "$MAIN_BUS" "$a"; then result "i2c $n" PASS "bus $MAIN_BUS $a answers"; else result "i2c $n" FAIL "bus $MAIN_BUS $a does not answer"; fi
    done
    if [ -n "${IMU_ADDR:-}" ]; then
      id=$(i2cget -y -f "$MAIN_BUS" "$IMU_ADDR" 0x0F 2>/dev/null)          # WHO_AM_I
      if [ "$id" = "${IMU_ID:-0x6b}" ]; then result "motion sensor" PASS "ISM330DHCX WHO_AM_I $id"
      else result "motion sensor" FAIL "WHO_AM_I '${id:-none}' at $IMU_ADDR, ${IMU_ID:-0x6b} expected"; fi
    fi
    if have i2ctransfer; then
      if [ -n "${EEPROM_ADDR:-}" ]; then
        b=$(i2ctransfer -y -f "$MAIN_BUS" w1@"$EEPROM_ADDR" 0x00 r8 2>/dev/null)
        if [ -n "$b" ]; then result "id chip" PASS "24AA02 at $EEPROM_ADDR, first bytes $b"; else result "id chip" FAIL "24AA02 at $EEPROM_ADDR does not answer"; fi
      fi
      if [ -n "${SE_ADDR:-}" ]; then   # ATECC608: a write to address 0 holds SDA low for 8 bit times to wake it
        # tWLO >= 60 us (DS40002239B Table 2-2): 8 bits are 80 us at 100 kHz but 20 us at 400 kHz, so the main bus
        # runs at 100 kHz (device tree, board profile MAIN_BUS_HZ). The bus clock is read from the device tree.
        hz=$(od -An -tu1 "$SYS/bus/i2c/devices/i2c-$MAIN_BUS/of_node/clock-frequency" 2>/dev/null | awk '{for (i=1;i<=NF;i++) v=v*256+$i} END {if (NR) print v}')
        i2ctransfer -y -f "$MAIN_BUS" w1@0x00 0x00 >/dev/null 2>&1
        w=$(i2ctransfer -y -f "$MAIN_BUS" r4@"$SE_ADDR" 2>/dev/null)
        if [ "$w" = "0x04 0x11 0x33 0x43" ]; then result "security chip" PASS "ATECC608 at $SE_ADDR woke (04 11 33 43)${hz:+, bus $((hz / 1000)) kHz}"
        elif [ -n "$hz" ] && [ "$hz" -gt 100000 ]; then result "security chip" FAIL "ATECC608 at $SE_ADDR did not wake: bus $MAIN_BUS runs at $((hz / 1000)) kHz, so the wake byte holds SDA low $((8000000 / hz)) us, under the 60 us it needs; set the bus to 100 kHz in the device tree"
        else result "security chip" FAIL "ATECC608 at $SE_ADDR wake answer '${w:-none}', 0x04 0x11 0x33 0x43 expected${hz:+ (bus $((hz / 1000)) kHz)}"; fi
        i2ctransfer -y -f "$MAIN_BUS" w1@"$SE_ADDR" 0x01 >/dev/null 2>&1   # word address 1: sleep
      fi
    else result "id and security chips" SKIP "i2ctransfer not installed"; fi
  fi
  if [ -n "${CAM_BUS:-}" ] && [ -n "${CAM_SENSOR_ADDR:-}" ] && have i2ctransfer; then
    id=$(i2ctransfer -y -f "$CAM_BUS" w2@"$CAM_SENSOR_ADDR" 0x30 0x0a r2 2>/dev/null)   # chip id 300Ah-300Bh
    if [ "$id" = "${CAM_ID:-0x92 0x81}" ]; then result "camera sensor" PASS "OV9281 chip id $id at $CAM_SENSOR_ADDR"
    else result "camera sensor" FAIL "chip id '${id:-none}' at $CAM_SENSOR_ADDR, ${CAM_ID:-0x92 0x81} expected"; fi
  fi
  if [ -n "${LED_ADDR:-}" ] && [ -n "${LED_BUS:-}" ]; then
    if i2c_has "$LED_BUS" "$LED_ADDR"; then result "light driver" PASS "IS31FL3216 at $LED_ADDR answers"
    else result "light driver" FAIL "IS31FL3216 at $LED_ADDR does not answer"; fi
  fi
}

# ---------------------------------------------------------------- cameras: each one in the profile streams 30 frames
frame_stats() {  # frame_stats <file> <bytes>: "mean spread" of the first frame, sampled every 61st byte
  dd if="$1" bs="$2" count=1 2>/dev/null | od -An -v -tu1 -w61 | awk '{s+=$1; q+=$1*$1; n++} END {if (n==0) {print "0 0"; exit} m=s/n; v=q/n-m*m; if (v<0) v=0; printf "%.0f %.1f\n", m, sqrt(v)}'
}
t_cameras() {
  say "== cameras: each streams ${CAM_FRAMES:-30} frames, ${CAM_W}x${CAM_H} ${CAM_FMT}"
  have v4l2-ctl || { result cameras SKIP "v4l2-ctl not installed"; return; }
  [ -n "${CAMERAS:-}" ] || { result cameras SKIP "no cameras in the profile"; return; }
  for c in $CAMERAS; do                # A=/dev/video0:0 (node, switch channel)
    name=${c%%=*}; rest=${c#*=}; node=${rest%%:*}; ch=${rest#*:}; [ "$ch" = "$rest" ] && ch=""
    [ -n "$ch" ] && mux "$ch"
    if [ -n "${CAM_SETUP:-}" ]; then sh -c "$CAM_SETUP $name" >> "$LOG" 2>&1; fi
    if [ ! -e "$DEVFS$node" ]; then result "camera $name" FAIL "$node not present"; continue; fi
    f="$TMP/cam-$name.raw"; rm -f "$f"
    if [ -n "$ch" ] && [ -n "${CAM_SENSOR_ADDR:-}" ] && ! i2c_has "$CAM_BUS" "$CAM_SENSOR_ADDR"; then
      result "camera $name" FAIL "sensor does not answer at $CAM_SENSOR_ADDR (switch channel $ch)"; continue; fi
    v4l2-ctl -d "$node" --set-fmt-video=width="$CAM_W",height="$CAM_H",pixelformat="$CAM_FMT" >> "$LOG" 2>&1
    v4l2-ctl -d "$node" --stream-mmap=4 --stream-count="${CAM_FRAMES:-30}" --stream-to="$f" > "$TMP/v4l2.txt" 2>&1
    rc=$?; fb=$((CAM_W * CAM_H * ${CAM_BPP:-1})); size=$(wc -c < "$f" 2>/dev/null || echo 0); got=$((size / fb))
    fps=$(grep -o '[0-9.]* fps' "$TMP/v4l2.txt" | tail -1)
    set -- $(frame_stats "$f" "$fb"); mean=$1; spread=$2
    if [ $rc -ne 0 ] || [ "$got" -lt "${CAM_FRAMES:-30}" ]; then
      result "camera $name" FAIL "$got of ${CAM_FRAMES:-30} frames received (v4l2-ctl exit $rc) on $node"
    elif awk "BEGIN{exit !($spread < 2.0)}"; then
      result "camera $name" FAIL "$got frames but the picture is flat (mean $mean, spread $spread): lens cap, no light or a dead sensor"
    else
      result "camera $name" PASS "$got frames received, ${fps:-? fps}, picture mean $mean spread $spread, on $node"
    fi
    cp "$f" "$OUT/camera-$name.raw" 2>/dev/null; dd if="$f" of="$OUT/camera-$name-frame1.gray" bs="$fb" count=1 2>/dev/null
  done
  [ -n "${MUX_ADDR:-}" ] && mux off
}

# ---------------------------------------------------------------- fps: the camera at full rate for 10 s
cam_subdev() {  # the sensor's own V4L2 sub-device: the profile's CAM_SUBDEV, else the one named ov9281
  [ -n "${CAM_SUBDEV:-}" ] && { echo "$CAM_SUBDEV"; return; }
  for n in "$SYS"/class/video4linux/v4l-subdev*/name; do
    grep -qi 'ov9281\|ov9282' "$n" 2>/dev/null && { d=${n%/name}; echo "/dev/${d##*/}"; return; }
  done
}
t_fps() {
  secs=${CAM_FPS_SECONDS:-10}; want=${CAM_FPS:-120}; min=${CAM_FPS_MIN:-119}
  say "== camera speed: $secs s at full rate, ${CAM_W}x${CAM_H}: $min fps or more in every second, no frame lost"
  have v4l2-ctl || { result fps SKIP "v4l2-ctl not installed"; return; }
  [ -n "${CAMERAS:-}" ] || { result fps SKIP "no cameras in the profile"; return; }
  for c in $CAMERAS; do
    name=${c%%=*}; rest=${c#*=}; node=${rest%%:*}
    [ -e "$DEVFS$node" ] || { result "fps $name" FAIL "$node not present"; continue; }
    if [ -n "${CAM_SETUP:-}" ]; then sh -c "$CAM_SETUP $name" >> "$LOG" 2>&1; fi
    sd=$(cam_subdev)
    if [ -n "$sd" ]; then   # the shortest vertical blanking the driver allows is the sensor's top frame rate
      vb=$(v4l2-ctl -d "$sd" -l 2>/dev/null | sed -n 's/.*vertical_blanking.*min=\([0-9]*\).*/\1/p' | head -1)
      [ -n "$vb" ] && v4l2-ctl -d "$sd" -c vertical_blanking="$vb" >> "$LOG" 2>&1 && say "   $sd: vertical blanking $vb (the top rate)"
    fi
    v4l2-ctl -d "$node" --set-fmt-video=width="$CAM_W",height="$CAM_H",pixelformat="$CAM_FMT" >> "$LOG" 2>&1
    n=$((want * secs)); t0=$(date +%s)
    v4l2-ctl -d "$node" --stream-mmap=8 --stream-count="$n" --stream-to=/dev/null > "$TMP/fps.txt" 2>&1; rc=$?
    dt=$(( $(date +%s) - t0 )); [ $dt -lt 1 ] && dt=1
    tr '<\r' '\n\n' < "$TMP/fps.txt" | grep 'fps' > "$TMP/fps-lines.txt"
    rates=$(grep -o '[0-9.]* fps' "$TMP/fps-lines.txt" | awk '{print $1}')
    last=$(echo "$rates" | tail -1); low=$(echo "$rates" | sed '1d' | sort -n | head -1)   # the first second is start-up
    [ -n "$low" ] || low=$last; [ -n "$last" ] || { last=$((n / dt)); low=$last; }
    lost=$(grep -o 'dropped buffers: [0-9]*' "$TMP/fps-lines.txt" | awk '{s += $3} END {print s + 0}')   # per print: v4l2-ctl's fps_timestamps::dropped() resets
    cp "$TMP/fps.txt" "$OUT/camera-$name-fps.txt" 2>/dev/null
    if [ $rc -ne 0 ]; then result "fps $name" FAIL "the stream stopped after about $dt s (v4l2-ctl exit $rc)"
    elif [ "$lost" -gt 0 ]; then result "fps $name" FAIL "$lost frames lost in $n ($last fps)"
    elif awk "BEGIN{exit !($low >= $min)}"; then result "fps $name" PASS "$n frames, $last fps, slowest second $low fps, none lost"
    else result "fps $name" FAIL "slowest second $low fps ($last fps at the end), $min needed"; fi
  done
}

# ---------------------------------------------------------------- lights: 8 red/green lights, each red, then each green
# Each light is one red/green LED: OUT1-8 drive lights 1-8 red, OUT9-16 the same lights green (circuit.mjs, D11-D18).
led() {  # led <out 1-16|0 for all off> <pwm>
  b=$LED_BUS; a=$LED_ADDR
  if [ "$1" = 0 ]; then i2cset -y "$b" "$a" 0x01 0x00 && i2cset -y "$b" "$a" 0x02 0x00 && i2cset -y "$b" "$a" 0xB0 0x00; return; fi
  o=$1; reg=$((0x20 - o))           # PWM register 10h is OUT16 ... 1Fh is OUT1
  i2cset -y "$b" "$a" "$reg" "$2" || return 1
  if [ "$o" -le 8 ]; then i2cset -y "$b" "$a" 0x01 0x00 && i2cset -y "$b" "$a" 0x02 $((1 << (o - 1)))
  else i2cset -y "$b" "$a" 0x02 0x00 && i2cset -y "$b" "$a" 0x01 $((1 << (o - 9))); fi
  i2cset -y "$b" "$a" 0xB0 0x00
}
t_lights() {
  say "== lights: each of the 8 lights red, then each green, in turn; then all red, all green, all amber (watch both edges of the camera head)"
  [ -n "${LED_ADDR:-}" ] || { result lights SKIP "no light driver in the profile"; return; }
  have i2cset || { result lights SKIP "i2c-tools not installed"; return; }
  [ -n "${LED_MUX_CH:-}" ] && mux "$LED_MUX_CH"
  if ! i2c_has "$LED_BUS" "$LED_ADDR"; then result lights FAIL "IS31FL3216 at $LED_ADDR does not answer"; return; fi
  # normal operation, PWM mode; OUT9-16 as current outputs (not GPIO); full current scale
  i2cset -y "$LED_BUS" "$LED_ADDR" 0x00 0x00 && i2cset -y "$LED_BUS" "$LED_ADDR" 0x04 0x00 &&
    i2cset -y "$LED_BUS" "$LED_ADDR" 0x05 0x00 && i2cset -y "$LED_BUS" "$LED_ADDR" 0x03 0x00 ||
    { result lights FAIL "the driver did not take its set-up"; return; }
  bad=""
  for o in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16; do
    col=red; n=$o; [ "$o" -gt 8 ] && col=green && n=$((o - 8))   # light n, its red or green
    led "$o" 0xC0 || bad="$bad $col$n"; say "  light $n $col"; sleep "${LED_STEP:-0.4}"
  done
  led 0 0
  for col in red green amber; do   # every light together: red OUT, green NOT OUT, both = amber (no-ball, wide)
    case $col in red) i2cset -y "$LED_BUS" "$LED_ADDR" 0x02 0xFF ;; green) i2cset -y "$LED_BUS" "$LED_ADDR" 0x01 0xFF ;;
      amber) i2cset -y "$LED_BUS" "$LED_ADDR" 0x02 0xFF && i2cset -y "$LED_BUS" "$LED_ADDR" 0x01 0xFF ;; esac
    i2cset -y "$LED_BUS" "$LED_ADDR" 0xB0 0x00; say "  all $col on"; sleep 1; led 0 0
  done
  [ -n "${LED_MUX_CH:-}" ] && mux off
  if [ -n "$bad" ]; then result lights FAIL "the driver refused:$bad"
  elif ask "Did each light show red, then green, in turn on both edges, then all red, all green and all amber?"; then
    result lights PASS "8 lights red and green in turn, then all red, all green, all amber"
  else result lights FAIL "operator saw a light missing"; fi
}

# ---------------------------------------------------------------- speaker: 1 kHz tone, then the word "out"
tone() {  # tone <seconds> > raw U8 8 kHz mono, 1 kHz square wave at a quarter of full scale (-12 dBFS)
  # A square wave's rms equals its peak: at 1/4 scale the amplifier (9 dB, 3.6 V rms for a full-scale sine) puts
  # (0.25 x 5.09 V)^2 / 4 ohm = 0.4 W (est.) into the 2 W speaker, about 96 dB SPL at 10 cm. At 3/4 scale it would be
  # 3.6 W, over the speaker's rating and the -2 dBFS (2.0 W) software cap (FINISH.md 8 Nov 22:30).
  s='\240\240\240\240\140\140\140\140'; r="$s"; i=0
  while [ $i -lt 10 ]; do r="$r$r"; i=$((i+1)); done      # 1024 cycles, about 1 s
  n=0; while [ $n -lt "$1" ]; do printf "$r"; n=$((n+1)); done
}
t_speaker() {
  say "== speaker: a 1 kHz tone for 1 s, then the word \"out\""
  have aplay || { result speaker SKIP "aplay not installed"; return; }
  [ -n "${SPK_DEV:-}" ] || { result speaker SKIP "no speaker in the profile"; return; }
  [ -n "${AMP_ON:-}" ] && sh -c "$AMP_ON" >> "$LOG" 2>&1
  tone 1 > "$TMP/tone.u8"
  aplay -q -D "$SPK_DEV" -t raw -f U8 -r 8000 -c 1 "$TMP/tone.u8" 2>> "$LOG"; rc=$?
  w=$HERE/out.wav; [ -f "$w" ] && { sleep 0.3; aplay -q -D "$SPK_DEV" "$w" 2>> "$LOG" || rc=1; }
  if [ $rc -ne 0 ]; then result speaker FAIL "aplay could not play on $SPK_DEV (see iemi-test.log)"
  elif ask "Did you hear a clear tone, then the word \"out\"?"; then result speaker PASS "tone and \"out\" played on $SPK_DEV"
  else result speaker FAIL "operator did not hear the tone or the word"; fi
}

# ---------------------------------------------------------------- mic: two taps (or, with --auto, the speaker's tone)
# Levels come from the recorded samples, in dB below full scale (dBFS), not from arecord's meter: the meter shows
# whole percent of full scale, and the IM63D135A's full scale is 135 dB SPL (-41 dBFS at 94 dB SPL, Table 7), so a
# room is about -80 dBFS (0.01 %) and the speaker's test tone about -40 dBFS (1 %); a clipped tap reads "MAX".
mic_levels() {  # mic_levels <wav>: one line per 50 ms window, "<peak dBFS> <1 kHz dBFS>" (S16_LE mono, 44-byte header)
  od -An -v -td2 -j44 "$1" | tr -s ' ' '\n' | awk -v rate=16000 '
    function db(v) { return v < 0.01 ? -130 : 20 * log(v / 32768) / log(10) }
    BEGIN { N = rate / 20; c = 2 * cos(2 * atan2(0, -1) * 1000 / rate) }   # Goertzel at 1 kHz: 50 whole cycles a window
    NF { x = $1; a = x < 0 ? -x : x; if (a > pk) pk = a; s0 = x + c * s1 - s2; s2 = s1; s1 = s0
         if (++n == N) { p = s1 * s1 + s2 * s2 - c * s1 * s2; if (p < 0) p = 0
                         printf "%.1f %.1f\n", db(pk), db(2 * sqrt(p) / N); pk = 0; s1 = 0; s2 = 0; n = 0 } }'
}
t_mic() {
  have arecord || { result mic SKIP "arecord not installed"; return; }
  [ -n "${MIC_DEV:-}" ] || { result mic SKIP "no microphone in the profile"; return; }
  say "== mic: 1 s of quiet first"
  arecord -D "$MIC_DEV" -f S16_LE -r 16000 -c 1 -d 1 "$TMP/q.wav" > /dev/null 2>> "$LOG"
  [ -s "$TMP/q.wav" ] || { result mic FAIL "arecord got nothing from $MIC_DEV"; return; }
  if od -An -v -td2 -j44 "$TMP/q.wav" | tr -s ' ' '\n' | awk 'NF { if (n++ && $1 != a) { m = 1; exit } a = $1 } END { exit m }'; then
    result mic FAIL "the microphone sends one value only: no PDM clock, or its data line stuck"; return; fi
  mic_levels "$TMP/q.wav" > "$TMP/q.lv"
  qpk=$(sort -n "$TMP/q.lv" | tail -1 | cut -d' ' -f1); q1k=$(cut -d' ' -f2 "$TMP/q.lv" | sort -n | tail -1)
  if [ "$AUTO" = 1 ] && [ -n "${SPK_DEV:-}" ]; then
    th=$(awk -v q="$q1k" -v d="${MIC_TONE_DB:-20}" -v m="${MIC_TONE_MIN_DBFS:--70}" 'BEGIN { t = q + d; if (t < m) t = m; print t }')
    say "   listening to the speaker's 1 kHz tone (threshold $th dBFS, quiet $q1k dBFS at 1 kHz)"
    tone 2 > "$TMP/tone.u8"
    arecord -D "$MIC_DEV" -f S16_LE -r 16000 -c 1 -d 3 "$OUT/mic.wav" > /dev/null 2>> "$LOG" &
    sleep 0.5; aplay -q -D "$SPK_DEV" -t raw -f U8 -r 8000 -c 1 "$TMP/tone.u8" 2>> "$LOG"; wait
    mic_levels "$OUT/mic.wav" > "$TMP/m.lv"
    set -- $(awk -v th="$th" '{ if ($2 >= th) n++; if (NR == 1 || $2 > top) top = $2 } END { printf "%d %s\n", n, (NR ? top : -130) }' "$TMP/m.lv")
    if [ "$1" -ge 10 ]; then result mic PASS "heard the speaker's tone at $2 dBFS for $(($1 * 50)) ms (quiet $q1k dBFS, threshold $th)"
    else result mic FAIL "the speaker's tone reached $2 dBFS, over $th dBFS for $(($1 * 50)) ms of 2 s (quiet $q1k dBFS)"; fi
    return
  fi
  th=$(awk -v q="$qpk" -v d="${MIC_TAP_DB:-20}" -v m="${MIC_TAP_MIN_DBFS:--50}" 'BEGIN { t = q + d; if (t < m) t = m; print t }')
  say "   now tap the main board next to the microphone twice, about half a second apart (3 s)"
  arecord -D "$MIC_DEV" -f S16_LE -r 16000 -c 1 -d 3 "$OUT/mic.wav" > /dev/null 2>> "$LOG"
  mic_levels "$OUT/mic.wav" > "$TMP/m.lv"
  set -- $(awk -v th="$th" '{ if ($1 >= th && !up) { n++; up = 1; gap = 0 } else if ($1 < th - 10) { if (++gap >= 3) up = 0 }
    if (NR == 1 || $1 > top) top = $1 } END { printf "%d %s\n", n, (NR ? top : -130) }' "$TMP/m.lv")
  if [ "$1" -ge 2 ]; then result mic PASS "$1 taps heard (peak $2 dBFS, threshold $th dBFS, quiet $qpk dBFS)"
  else result mic FAIL "$1 tap(s) heard, 2 needed (peak $2 dBFS, threshold $th dBFS, quiet $qpk dBFS)"; fi
}

# ---------------------------------------------------------------- power: the fuel gauge (MAX17260 at 0x36)
word() { i2cget -y -f "$1" "$2" "$3" w 2>/dev/null; }   # -f as i2c_has
t_power() {
  [ -n "${GAUGE_ADDR:-}" ] || { result power SKIP "no fuel gauge in the profile"; return; }
  have i2cget || { result power SKIP "i2c-tools not installed"; return; }
  v=$(word "$MAIN_BUS" "$GAUGE_ADDR" 0x09); s=$(word "$MAIN_BUS" "$GAUGE_ADDR" 0x06); c=$(word "$MAIN_BUS" "$GAUGE_ADDR" 0x0A)
  [ -n "$v" ] || { result power FAIL "MAX17260 at $GAUGE_ADDR does not answer"; return; }
  mv=$(( $(printf '%d' "$v") * 78125 / 1000000 )); pct=$(( $(printf '%d' "$s") / 256 ))
  ci=$(printf '%d' "$c"); [ "$ci" -ge 32768 ] && ci=$((ci - 65536))
  ma=$(( ci * 15625 / (${RSENSE_MOHM:-10} * 10000) ))   # 1.5625 uV / Rsense per bit
  if [ "$mv" -ge 2500 ] && [ "$mv" -le 3700 ]; then result power PASS "cell $mv mV, $pct %, current $ma mA (+ is charging)"
  else result power FAIL "cell voltage $mv mV outside 2500-3700 mV"; fi
}

# ---------------------------------------------------------------- charger: LTC4162-F at 0x68 (refs/ltc4162f, register map)
# chem (0x43 bits 11-8): 6 the -FST (3.6 V fixed), 4 the -FAD alternate; with USB in it reports 1 cell, the input
# voltage (1.649 mV/bit), the charge current (1.466 uV / R86 per bit) and the die temperature (0.0215 C/bit - 264.4)
sword() { v=$(word "$MAIN_BUS" "$CHG_ADDR" "$1"); [ -n "$v" ] || return 1; v=$(printf '%d' "$v"); [ "$v" -ge 32768 ] && v=$((v - 65536)); echo "$v"; }
t_charger() {
  [ -n "${CHG_ADDR:-}" ] || { result charger SKIP "no charger in the profile"; return; }
  have i2cget || { result charger SKIP "i2c-tools not installed"; return; }
  cc=$(word "$MAIN_BUS" "$CHG_ADDR" 0x43) || cc=""
  [ -n "$cc" ] || { result charger FAIL "LTC4162 at $CHG_ADDR does not answer"; return; }
  cc=$(printf '%d' "$cc"); chem=$(( (cc >> 8) & 15 )); cells=$(( cc & 15 ))
  # finding AU: the charger slows its charge from 100 C die and stops at 110 C (the cells are guarded by TH2 and JEITA) (LTC4162-F p.22: thermal_reg_start_temp 0x10,
  # thermal_reg_end_temp 0x11, (T + 264.4) / 0.0215; the defaults are 120/125 C). The stump program writes the same at every boot.
  if have i2cset; then i2cset -y "$MAIN_BUS" "$CHG_ADDR" 0x10 0x4235 w 2>/dev/null; i2cset -y "$MAIN_BUS" "$CHG_ADDR" 0x11 0x4406 w 2>/dev/null
    ts=$(word "$MAIN_BUS" "$CHG_ADDR" 0x10); [ "$(printf '%d' "${ts:-0}")" = 16949 ] || { result charger FAIL "thermal limit write did not hold (0x10 reads ${ts:-nothing})"; return; }; fi
  case "$chem" in 6) part="LTC4162-FST" ;; 4) part="LTC4162-FAD" ;; *) result charger FAIL "chemistry code $chem: not a LiFePO4 LTC4162-F (6 FST, 4 FAD)"; return ;; esac
  if [ "$AUTO" != 1 ]; then say "   plug a 3 A USB-C charger in, and keep it in while you press Enter"; read -r _; sleep 3; fi
  cc=$(printf '%d' "$(word "$MAIN_BUS" "$CHG_ADDR" 0x43)"); cells=$(( cc & 15 ))
  if [ "$cells" = 0 ]; then
    if [ "$AUTO" = 1 ]; then result charger PASS "$part answers; no USB input, so no charge check"; else result charger FAIL "$part sees no USB input (cell count 0)"; fi; return
  fi
  vin=$(sword 0x3B); ib=$(sword 0x3D); dt=$(sword 0x3F); st=$(printf '%d' "$(word "$MAIN_BUS" "$CHG_ADDR" 0x35)")
  vmv=$(( vin * 1649 / 1000 )); ima=$(( ib * 1466 / (${RSNSB_MOHM:-10} * 1000) )); tc=$(( (dt * 215 - 2644000) / 10000 ))
  if [ "$cells" = 1 ] && [ "$vmv" -ge 4500 ] && [ "$ima" -gt 100 ]; then result charger PASS "$part, 1 cell, input $vmv mV, charging $ima mA, die $tc C, status $st"
  else result charger FAIL "$part: cells $cells, input $vmv mV, charge $ima mA (want 1 cell, 4500 mV or more, over 100 mA), status $st"; fi
}

# ---------------------------------------------------------------- bails: the two Hall switches
gpio_read() { # gpio_read <chip> <line>
  if have gpioget; then gpioget "$1" "$2" 2>/dev/null || gpioget -c "$1" "$2" 2>/dev/null | grep -o '[01]$\|active\|inactive'
  else cat "$SYS/class/gpio/gpio$2/value" 2>/dev/null; fi
}
t_bails() {
  [ -n "${HALL_L:-}" ] || { result bails SKIP "no bail lines in the profile"; return; }
  for side in L R; do
    eval spec=\$HALL_$side; chip=${spec%%:*}; line=${spec#*:}
    a=$(gpio_read "$chip" "$line")
    if [ "$AUTO" = 1 ]; then
      if [ -n "$a" ]; then result "bail $side" PASS "line reads $a with no magnet"; else result "bail $side" FAIL "line $spec unreadable"; fi
      continue
    fi
    say "   bail $side: hold the test magnet over the $side bail sensor, then press Enter"; read -r _
    b=$(gpio_read "$chip" "$line")
    if [ -n "$a" ] && [ "$a" != "$b" ]; then result "bail $side" PASS "line $spec changed $a -> $b with the magnet"
    else result "bail $side" FAIL "line $spec read $a then $b: no change with the magnet"; fi
  done
}

# ---------------------------------------------------------------- sd, wifi
t_sd() {
  dev=$(awk '$2=="/" {print $1}' "$PROC/mounts" 2>/dev/null | head -1)
  f=$OUT/.iemi-sd-test; t0=$(date +%s)
  if dd if=/dev/zero of="$f" bs=1M count=64 conv=fsync 2>/dev/null; then
    t1=$(date +%s); dt=$((t1 - t0)); [ $dt -lt 1 ] && dt=1; rm -f "$f"
    if [ $((64 / dt)) -ge 10 ]; then result sd PASS "64 MB written in $dt s on $dev"; else result sd FAIL "64 MB took $dt s on $dev (needs 10 MB/s)"; fi
  else result sd FAIL "could not write 64 MB in $OUT"; fi
}
t_wifi() {
  [ -n "${WIFI_IF:-}" ] || { result wifi SKIP "no Wi-Fi interface in the profile"; return; }
  if [ ! -d "$SYS/class/net/$WIFI_IF" ] && ! ip link show "$WIFI_IF" >/dev/null 2>&1; then
    result wifi FAIL "$WIFI_IF not present (Wi-Fi module, its SDIO lines or its firmware)"; return; fi
  ip link set "$WIFI_IF" up 2>/dev/null
  (iw dev "$WIFI_IF" scan 2>/dev/null || iwlist "$WIFI_IF" scan 2>/dev/null) > "$TMP/scan.txt"
  n=$(grep -c 'SSID' "$TMP/scan.txt")
  best=$(grep -o 'signal: -[0-9.]*\|Signal level=-[0-9]*' "$TMP/scan.txt" | grep -o '\-[0-9]*' | sort -n | tail -1)
  if [ "$n" -ge 1 ]; then result "wifi scan" PASS "$WIFI_IF sees $n networks, strongest ${best:-?} dBm"
  else result "wifi scan" FAIL "$WIFI_IF sees no networks (antenna, its match or the 37.4 MHz reference)"; fi
  if have iw; then
    iw list > "$TMP/iw.txt" 2>/dev/null
    if grep -A12 'Supported interface modes' "$TMP/iw.txt" | grep -q '\* AP'; then result "wifi access point" PASS "AP mode supported (the stumps' own network)"
    else result "wifi access point" FAIL "AP mode not listed: the stumps' network needs it"; fi
    if [ -n "${WIFI_5G:-}" ]; then
      if grep -q '\* 5[0-9][0-9][0-9]\(\.0\)\{0,1\} MHz' "$TMP/iw.txt"; then result "wifi 5 GHz" PASS "5 GHz channels listed"
      else result "wifi 5 GHz" FAIL "no 5 GHz channel listed"; fi
    fi
  fi
  if [ -n "${WIFI_PEER:-}" ] && have iperf3; then   # an iperf3 server on the same Wi-Fi: iperf3 -s on a laptop
    mb=$(iperf3 -c "$WIFI_PEER" -t 5 -f m 2>/dev/null | awk '/receiver/ {print int($(NF-2))}')
    if [ "${mb:-0}" -ge "${WIFI_MIN_MBPS:-10}" ]; then result "wifi speed" PASS "$mb Mbit/s to $WIFI_PEER"
    else result "wifi speed" FAIL "${mb:-0} Mbit/s to $WIFI_PEER, ${WIFI_MIN_MBPS:-10} needed"; fi
  else result "wifi speed" SKIP "set WIFI_PEER to an iperf3 server on the same Wi-Fi to measure"; fi
}
t_bt() {
  [ -n "${BT_DEV:-}" ] || { result bluetooth SKIP "no Bluetooth in the profile"; return; }
  if [ -e "$SYS/class/bluetooth/$BT_DEV" ] || { have hciconfig && hciconfig "$BT_DEV" >/dev/null 2>&1; }; then
    a=$( { hciconfig "$BT_DEV" 2>/dev/null | grep -o 'BD Address: [0-9A-F:]*'; } || true)
    result bluetooth PASS "controller $BT_DEV present ${a:+($a)}"
  else result bluetooth FAIL "no $BT_DEV: the AP6256's Bluetooth UART or its firmware"; fi
}

# ---------------------------------------------------------------- switches: tamper, power key
line_test() {  # line_test <name> <chip:line> <what the operator does>
  [ -n "$2" ] || { result "$1" SKIP "not in the profile"; return; }
  chip=${2%%:*}; line=${2#*:}; a=$(gpio_read "$chip" "$line")
  [ -n "$a" ] || { result "$1" FAIL "line $2 unreadable"; return; }
  if [ "$AUTO" = 1 ]; then result "$1" PASS "line $2 reads $a"; return; fi
  say "   $3, and keep it so while you press Enter"; read -r _
  b=$(gpio_read "$chip" "$line")
  if [ "$a" != "$b" ]; then result "$1" PASS "line $2 changed $a -> $b"; else result "$1" FAIL "line $2 stayed $a"; fi
}
t_switches() {
  line_test tamper "${TAMPER:-}" "press the tamper switch in"
  line_test "power key" "${PWR_INT:-}" "press and hold the power button, under 4 s (a 4 s hold switches the unit off)"
}

# ---------------------------------------------------------------- run
say "iemi-test $VERSION on board $BOARD: $WHAT"
case "$WHAT" in
  all) t_probe; t_system; t_chips; t_power; t_charger; t_sd; t_wifi; t_bt; t_cameras; t_fps; t_lights; t_speaker; t_mic; t_bails; t_switches ;;
  sound) t_speaker; t_mic ;;
  probe|system|chips|cameras|fps|lights|speaker|mic|power|charger|bails|switches|sd|wifi|bt) "t_$WHAT" ;;
  *) echo "unknown test $WHAT"; exit 2 ;;
esac
verdict=PASS; [ $NFAIL -gt 0 ] && verdict=FAIL
serial=$( { tr -d '\0' < /proc/device-tree/serial-number; } 2>/dev/null || cat /etc/machine-id 2>/dev/null)
printf '{"tool":"iemi-test","version":"%s","board":"%s","serial":"%s","time":"%s","what":"%s","pass":%d,"fail":%d,"skip":%d,"verdict":"%s","results":[%s]}\n' \
  "$VERSION" "$BOARD" "$serial" "$(date -u +%FT%TZ)" "$WHAT" $NPASS $NFAIL $NSKIP "$verdict" "$RESULTS" > "$JSON"
say "$verdict  ($NPASS pass, $NFAIL fail, $NSKIP skip) -> $JSON"
[ "$verdict" = PASS ]
