#!/usr/bin/env bash
# CricketOne P1 stump setup for a Raspberry Pi Zero 2 W running Raspberry Pi OS Lite (64-bit, Bookworm or later).
# Turns on the camera, I2C and SPI, installs the drivers and tools the bring-up test needs, and sets up clock sync.
# Usage on the Pi:  curl -fsSLO https://iemilabs.com/downloads/cricketone/install-stump.sh && sudo bash install-stump.sh
# Untested on real parts until the P1 order arrives (bench test B1); report problems in the build log.
set -euo pipefail

if [[ $EUID -ne 0 ]]; then echo "Run with sudo: sudo bash install-stump.sh"; exit 1; fi
CFG=/boot/firmware/config.txt; [[ -f $CFG ]] || CFG=/boot/config.txt
APP=/opt/cricketone
USER_NAME=${SUDO_USER:-pi}

echo "== 1/5 Camera, I2C and SPI in $CFG"
cp "$CFG" "$CFG.before-cricketone"
sed -i 's/^camera_auto_detect=1/camera_auto_detect=0/' "$CFG"
add() { grep -qxF "$1" "$CFG" || echo "$1" >> "$CFG"; }
add "# CricketOne P1"
add "camera_auto_detect=0"
add "dtoverlay=ov9281,arducam"
add "dtparam=i2c_arm=on"
add "dtparam=spi=on"

echo "== 2/5 Packages"
apt-get update
apt-get install -y python3-picamera2 python3-libcamera rpicam-apps python3-gpiozero python3-lgpio python3-smbus2 \
  python3-venv python3-pip i2c-tools chrony git

echo "== 3/5 Python libraries for the boards (in $APP/venv)"
mkdir -p "$APP"
python3 -m venv --system-site-packages "$APP/venv"
"$APP/venv/bin/pip" install --upgrade pip
"$APP/venv/bin/pip" install adafruit-blinka adafruit-circuitpython-ina219 adafruit-circuitpython-lsm6ds \
  adafruit-circuitpython-neopixel-spi
curl -fsSL https://iemilabs.com/downloads/cricketone/stump-bringup.py -o "$APP/stump-bringup.py"
chown -R "$USER_NAME":"$USER_NAME" "$APP"
usermod -aG i2c,spi,gpio,video "$USER_NAME"

echo "== 4/5 Wi-Fi power saving off (steadier timing) and clock sync"
cat > /etc/systemd/system/wifi-powersave-off.service <<'UNIT'
[Unit]
Description=Turn off Wi-Fi power saving for steady timing
After=network-online.target
[Service]
Type=oneshot
ExecStart=/usr/sbin/iw dev wlan0 set power_save off
[Install]
WantedBy=multi-user.target
UNIT
systemctl enable wifi-powersave-off.service
# The striker's middle stump (hostname stump-sm) serves time to the other five; it also follows the internet when it can.
if [[ "$(hostname)" == "stump-sm" ]]; then
  grep -q "^allow" /etc/chrony/chrony.conf || printf '\nallow 0.0.0.0/0\nlocal stratum 8\n' >> /etc/chrony/chrony.conf
else
  grep -q "stump-sm" /etc/chrony/chrony.conf || printf '\nserver stump-sm.local iburst minpoll 0 maxpoll 2 prefer\n' >> /etc/chrony/chrony.conf
fi
systemctl restart chrony

echo "== 5/5 Done. Reboot, then run the bring-up test:"
echo "   sudo reboot"
echo "   $APP/venv/bin/python $APP/stump-bringup.py"
