#!/usr/bin/env bash
#
# One-time system setup for the CH347 USB-I2C adapter and the RM3100 logger.
# Idempotent: safe to re-run.
#
# Needs sudo for exactly one thing: installing the udev rule that grants the
# plugdev group access to the adapter's USB node.

set -euo pipefail

VID=1a86
PID=55db
RULE_FILE=/etc/udev/rules.d/99-ch347.rules
RULE='SUBSYSTEM=="usb", ATTRS{idVendor}=="'"$VID"'", ATTRS{idProduct}=="'"$PID"'", GROUP="plugdev", MODE="0660"'

cd "$(dirname "$0")"

echo "== 1. Checking for the CH347 adapter =="
if ! lsusb -d "$VID:$PID" >/dev/null 2>&1; then
    echo "ERROR: no device $VID:$PID found on the USB bus." >&2
    echo "       Plug in the Waveshare adapter and make sure it is in Mode 1" >&2
    echo "       (UART1+I2C+SPI): DTR1 pulled high, RTS1 pulled low." >&2
    exit 1
fi
lsusb -d "$VID:$PID"

echo
echo "== 2. Installing udev rule =="
if [[ -f "$RULE_FILE" ]] && [[ "$(cat "$RULE_FILE")" == "$RULE" ]]; then
    echo "$RULE_FILE already up to date, skipping."
else
    echo "Writing $RULE_FILE (needs sudo)..."
    printf '%s\n' "$RULE" | sudo tee "$RULE_FILE" >/dev/null
    sudo udevadm control --reload-rules
    sudo udevadm trigger --subsystem-match=usb
    # udevadm trigger returns before the rule has necessarily been applied.
    sudo udevadm settle
    echo "Installed."
fi

if ! id -nG | tr ' ' '\n' | grep -qx plugdev; then
    echo "WARNING: $(id -un) is not in the 'plugdev' group, so the rule above" >&2
    echo "         will not grant access. Fix with:" >&2
    echo "             sudo usermod -aG plugdev $(id -un)" >&2
    echo "         then log out and back in." >&2
fi

echo
echo "== 3. Creating virtualenv and installing pyusb =="
if [[ ! -d .venv ]]; then
    python3 -m venv .venv
    echo "Created .venv"
else
    echo ".venv already exists"
fi
./.venv/bin/pip install --quiet --upgrade pip
./.venv/bin/pip install --quiet pyusb
echo "pyusb $(./.venv/bin/python -c 'import usb; print(usb.__version__)') installed"

echo
echo "== 4. Verifying device node permissions =="
# Resolve the bus/device path for this specific adapter.
NODE=$(lsusb -d "$VID:$PID" | head -1 |
       sed -E 's|Bus ([0-9]+) Device ([0-9]+).*|/dev/bus/usb/\1/\2|')
ls -l "$NODE"
if [[ -w "$NODE" ]]; then
    echo "OK: $NODE is writable by $(id -un)."
else
    echo "WARNING: $NODE is not writable by $(id -un)." >&2
    echo "         If the group above is already 'plugdev', unplug and replug" >&2
    echo "         the adapter so the new rule is applied to a fresh node." >&2
fi

echo
echo "Setup complete. Run the logger with:"
echo "    ./.venv/bin/python logger.py --duration 10"
echo "or, to check wiring only:"
echo "    ./.venv/bin/python logger.py --scan-only"
