#!/usr/bin/env bash
# can_setup.sh — Bring up CANable 2.0 (gs_usb) as can0
# Issue: https://gitea.vayrette.com/seb/saltylab-firmware/issues/643
#
# Usage:
#   sudo ./can_setup.sh               # bring up (default: 500kbps for VESC)
#   sudo ./can_setup.sh up dronecan   # bring up at 1Mbps for Here4 DroneCAN
#   sudo ./can_setup.sh down
#   sudo ./can_setup.sh verify        # candump one-shot check (Ctrl-C to stop)
#
# Bitrate modes:
#   default / vesc     — 500 kbps  (VESC IDs 0x3D/0x4F)
#   dronecan / here4   — 1000 kbps (CubePilot Here4 RTK GPS, DroneCAN default)
#
# CAN_BITRATE env var overrides both modes.
set -euo pipefail

IFACE="${CAN_IFACE:-can0}"

log() { echo "[can_setup] $*"; }
die() { echo "[can_setup] ERROR: $*" >&2; exit 1; }

cmd="${1:-up}"
mode="${2:-vesc}"

# Resolve bitrate: env var wins, then mode keyword, then 500k default
if [[ -n "${CAN_BITRATE:-}" ]]; then
    BITRATE="$CAN_BITRATE"
elif [[ "$mode" == "dronecan" || "$mode" == "here4" ]]; then
    BITRATE=1000000
else
    BITRATE=500000
fi

case "$cmd" in
  up)
    # Verify the interface exists (gs_usb module loaded by kernel on plug-in)
    if ! ip link show "$IFACE" &>/dev/null; then
        die "$IFACE not found — is CANable 2.0 plugged in and gs_usb loaded?"
    fi

    log "Bringing up $IFACE at ${BITRATE} bps (mode: ${mode})..."
    ip link set "$IFACE" down 2>/dev/null || true
    ip link set "$IFACE" up type can bitrate "$BITRATE"
    ip link set "$IFACE" up
    log "$IFACE is up."
    ip -details link show "$IFACE"
    ;;

  down)
    log "Bringing down $IFACE..."
    ip link set "$IFACE" down
    log "$IFACE is down."
    ;;

  verify)
    if [[ "$mode" == "dronecan" || "$mode" == "here4" ]]; then
        log "Listening on $IFACE — expecting DroneCAN frames from Here4 GPS (1Mbps)"
    else
        log "Listening on $IFACE — expecting frames from VESC IDs 0x3D (61) and 0x4F (79)"
    fi
    log "Press Ctrl-C to stop."
    exec candump "$IFACE"
    ;;

  *)
    echo "Usage: $0 [up [vesc|dronecan]|down|verify [dronecan]]"
    exit 1
    ;;
esac
