#!/usr/bin/env bash
#
# install-persistent.sh -- make the CaribouLite transmit fix survive a reboot.
#
# Two things revert on every boot and both have to be re-applied:
#
#   1. the ICE40 bitstream, which lives in SRAM, not flash
#   2. the kernel module, which reverts to whatever DKMS has installed
#
# This installs the patched driver as a new DKMS version (so it rebuilds
# itself against future kernels and auto-loads at boot) and adds a systemd
# oneshot that programs the FPGA early, before any userspace tool can
# program the *stock* bitstream over the top of it.
#
# Run it ON THE PI, pointing at the built transmission_fix tree:
#
#   sudo ./install-persistent.sh ~/cariboulite-txfix
#   sudo ./install-persistent.sh --uninstall
#
# See README.md in this directory for how that tree is built.

set -euo pipefail

PKG=smi-stream-dev
NEW_VER=1.1
OLD_VER=1.0
LIBDIR=/usr/local/lib/cariboulite
FLASHER=/usr/local/sbin/cariboulite-flash-fpga
BOOTHOOK=/usr/local/sbin/cariboulite-fpga-boot
UNIT=/etc/systemd/system/cariboulite-fpga.service

die() { printf 'install-persistent: error: %s\n' "$*" >&2; exit 1; }
say() { printf '==> %s\n' "$*"; }

[ "$(id -u)" = 0 ] || die "must run as root (use sudo)"
command -v dkms >/dev/null || die "dkms not installed (apt install dkms)"

# ---------------------------------------------------------------- uninstall
if [ "${1:-}" = "--uninstall" ]; then
    say "disabling the FPGA service"
    systemctl disable --now cariboulite-fpga.service 2>/dev/null || true
    rm -f "$UNIT"
    systemctl daemon-reload
    rm -f "$FLASHER" "$BOOTHOOK"
    rm -rf "$LIBDIR"
    if dkms status "$PKG/$NEW_VER" 2>/dev/null | grep -q .; then
        say "removing DKMS $PKG/$NEW_VER"
        dkms remove "$PKG/$NEW_VER" --all || true
    fi
    rm -rf "/usr/src/$PKG-$NEW_VER"
    if [ -d "/usr/src/$PKG-$OLD_VER" ]; then
        say "restoring the stock driver, DKMS $PKG/$OLD_VER"
        dkms add "$PKG/$OLD_VER" 2>/dev/null || true
        dkms build "$PKG/$OLD_VER" || die "stock driver failed to build"
        dkms install "$PKG/$OLD_VER" --force
    else
        say "WARNING: /usr/src/$PKG-$OLD_VER is gone; no stock driver to restore"
    fi
    say "done -- reboot to come up on the stock driver and bitstream"
    exit 0
fi

SRC="${1:-}"
[ -n "$SRC" ] || die "usage: $0 <path-to-built-transmission_fix-tree> | --uninstall"
SRC="$(cd -- "$SRC" && pwd)"

DRV="$SRC/driver"
BIN="$SRC/software/flash_fpga/build/flash_fpga"
BIT="$SRC/firmware/top.bin"
[ -f "$DRV/smi_stream_dev.c" ] || die "no driver source at $DRV"
[ -x "$BIN" ]                  || die "flash_fpga not built at $BIN"
[ -f "$BIT" ]                  || die "no bitstream at $BIT (run 'make firmware' on the host)"

grep -q SMI_CLASS_CREATE "$DRV/smi_stream_dev.c" \
    || die "$DRV/smi_stream_dev.c is not patched -- run patch_smi_txfix.py on it first"

# ------------------------------------------------------- 1. the kernel module
say "installing the patched driver as DKMS $PKG/$NEW_VER"
dkms remove "$PKG/$NEW_VER" --all 2>/dev/null || true
rm -rf "/usr/src/$PKG-$NEW_VER"
install -d "/usr/src/$PKG-$NEW_VER"
install -m 0644 "$DRV/smi_stream_dev.c" "$DRV/smi_stream_dev.h" \
                "$DRV/bcm2835_smi.h" "/usr/src/$PKG-$NEW_VER/"
printf 'obj-m += smi_stream_dev.o\nccflags-y += -O2\n' \
    > "/usr/src/$PKG-$NEW_VER/Makefile"

cat > "/usr/src/$PKG-$NEW_VER/dkms.conf" <<EOF
PACKAGE_NAME="$PKG"
PACKAGE_VERSION="$NEW_VER"

BUILT_MODULE_NAME[0]="smi_stream_dev"
DEST_MODULE_LOCATION[0]="/updates"

MAKE[0]="make -C \${kernel_source_dir} M=\${dkms_tree}/\${PACKAGE_NAME}/\${PACKAGE_VERSION}/build modules"
CLEAN="make -C \${kernel_source_dir} M=\${dkms_tree}/\${PACKAGE_NAME}/\${PACKAGE_VERSION}/build clean"

AUTOINSTALL="yes"
EOF

cat > "/usr/src/$PKG-$NEW_VER/PROVENANCE" <<EOF
Not the vendor driver. This is driver/smi_stream_dev.c from the
transmission_fix branch of https://github.com/matteoserva/cariboulite
(the unmerged fix from cariboulabs/cariboulite PR #197), with the
kernel-API compatibility shims from patch_smi_txfix.py applied so it
builds on kernels >= 6.4 / >= 6.11.

Without this driver the AT86RF215 never reaches I/Q sync and the board
transmits nothing -- see cariboulabs/cariboulite issue #189. The stock
driver remains at /usr/src/$PKG-$OLD_VER; install-persistent.sh
--uninstall puts it back.

Installed from: $SRC
EOF

dkms add "$PKG/$NEW_VER" 2>/dev/null || true
dkms build "$PKG/$NEW_VER" || die "DKMS build failed -- is the driver patched for this kernel?"
dkms install "$PKG/$NEW_VER" --force

# Only one DKMS version may provide smi_stream_dev, or which one wins at boot
# depends on DKMS ordering rather than on anything we chose.
if dkms status "$PKG/$OLD_VER" 2>/dev/null | grep -q installed; then
    say "removing the stock DKMS $PKG/$OLD_VER (source kept for --uninstall)"
    dkms remove "$PKG/$OLD_VER" --all \
        || say "WARNING: could not remove $PKG/$OLD_VER -- two versions now provide this module"
fi

# -------------------------------------------------- 2. the bitstream at boot
say "installing the bitstream, flasher and boot hook"
install -d "$LIBDIR"
install -m 0644 "$BIT" "$LIBDIR/top.bin"
install -m 0755 "$BIN" "$FLASHER"

cat > "$BOOTHOOK" <<EOF
#!/usr/bin/env bash
# Installed by install-persistent.sh -- do not edit, it will be overwritten.
#
# Programs the CaribouLite FPGA at boot and then binds the SMI streaming
# driver, in that order, which is the order the transmit fix was verified in.
set -u

BIT="\${1:-$LIBDIR/top.bin}"
FLASHER=$FLASHER

# udev may not have made the SPI and GPIO nodes yet when this runs.
for _ in \$(seq 1 60); do
    [ -e /dev/spidev1.0 ] && [ -e /dev/gpiochip0 ] && break
    sleep 0.5
done
if ! [ -e /dev/spidev1.0 ] || ! [ -e /dev/gpiochip0 ]; then
    echo "cariboulite-fpga-boot: SPI/GPIO nodes never appeared" >&2
    exit 1
fi

ok=0
for attempt in 1 2 3; do
    if out=\$("\$FLASHER" "\$BIT" 2>&1); then
        if printf '%s' "\$out" | grep -q 'FPGA programming - Success'; then
            echo "cariboulite-fpga-boot: programmed \$BIT (attempt \$attempt)"
            ok=1
            break
        fi
    fi
    echo "cariboulite-fpga-boot: attempt \$attempt failed" >&2
    printf '%s\n' "\$out" | tail -5 >&2
    sleep 1
done
[ "\$ok" = 1 ] || exit 1

# Rebind the driver so it comes up against a configured FPGA. A module that
# is in use is left where it is rather than failing the boot.
modprobe -r smi_stream_dev 2>/dev/null || true
modprobe bcm2835_smi || exit 1
modprobe smi_stream_dev || exit 1
echo "cariboulite-fpga-boot: driver loaded, srcversion \$(cat /sys/module/smi_stream_dev/srcversion 2>/dev/null)"
EOF
chmod 0755 "$BOOTHOOK"

cat > "$UNIT" <<EOF
[Unit]
Description=Program the CaribouLite FPGA and bind the SMI streaming driver
Documentation=https://github.com/cariboulabs/cariboulite/issues/189
# The ICE40 is configured into SRAM, so this is needed on every boot. It runs
# before anything in userspace can touch the radio: libcariboulite programs
# its own *stock* bitstream whenever it finds the FPGA unconfigured, which
# would silently undo the fix.
After=systemd-modules-load.service local-fs.target
Before=multi-user.target

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=$BOOTHOOK $LIBDIR/top.bin

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable cariboulite-fpga.service
say "enabled cariboulite-fpga.service"

say "running it now so the current boot matches"
systemctl restart cariboulite-fpga.service
systemctl --no-pager --lines=10 status cariboulite-fpga.service || true

cat <<EOF

Installed. On every boot the FPGA is programmed from $LIBDIR/top.bin and the
patched driver loads from DKMS, so it also rebuilds itself after a kernel
upgrade.

Check it with:
    systemctl status cariboulite-fpga.service
    cat /sys/module/smi_stream_dev/srcversion     # expect the patched one
    tx_test ... 2>&1 | grep "incoming I/Q"        # expect: 1

Undo with:
    sudo $0 --uninstall
EOF
