#!/usr/bin/env bash
set -euo pipefail

# This script installs prerequisites, sets up a venv, installs deps,
# and wires up systemd units on a Raspberry Pi.
# Run as: sudo bash scripts/pi_install.sh /home/pi/ecu_tests

TARGET_DIR="${1:-/home/pi/ecu_tests}"
REPO_URL="${2:-}"  # optional; if empty assumes repo already present at TARGET_DIR
PI_USER="${PI_USER:-pi}"

log() { echo "[pi_install] $*"; }

if [[ $EUID -ne 0 ]]; then
  echo "Please run as root (sudo)." >&2
  exit 1
fi

log "Installing OS packages..."
apt-get update -y
apt-get install -y --no-install-recommends \
  python3 python3-venv python3-pip git ca-certificates \
  libusb-1.0-0 udev

mkdir -p "$TARGET_DIR"
chown -R "$PI_USER":"$PI_USER" "$TARGET_DIR"

if [[ -n "$REPO_URL" ]]; then
  log "Cloning repo: $REPO_URL"
  sudo -u "$PI_USER" git clone "$REPO_URL" "$TARGET_DIR" || true
fi

cd "$TARGET_DIR"

log "Creating Python venv..."
sudo -u "$PI_USER" python3 -m venv .venv

log "Installing Python dependencies..."
sudo -u "$PI_USER" bash -lc "source .venv/bin/activate && pip install --upgrade pip && pip install -r requirements.txt"

log "Preparing reports directory..."
mkdir -p reports
chown -R "$PI_USER":"$PI_USER" reports

log "Installing systemd units..."
install -Dm644 scripts/ecu-tests.service /etc/systemd/system/ecu-tests.service
if [[ -f scripts/ecu-tests.timer ]]; then
  install -Dm644 scripts/ecu-tests.timer /etc/systemd/system/ecu-tests.timer
fi
systemctl daemon-reload
systemctl enable ecu-tests.service || true
if [[ -f /etc/systemd/system/ecu-tests.timer ]]; then
  systemctl enable ecu-tests.timer || true
fi

log "Installing udev rules (if provided)..."
# DEPRECATED: the babylin udev rule is only needed for the legacy BabyLIN USB
# adapter. MUM deployments do not require this and the block can be removed
# once no babylin hardware remains in the field.
if [[ -f scripts/99-babylin.rules ]]; then
  install -Dm644 scripts/99-babylin.rules /etc/udev/rules.d/99-babylin.rules
  udevadm control --reload-rules || true
  udevadm trigger || true
fi

log "Done. You can start the service with: systemctl start ecu-tests.service"