#!/usr/bin/env bash
# can_setup.sh — Bring up CANable 2.0 (gs_usb) as can0 at 500 kbps
# Issue: https://gitea.vayrette.com/seb/saltylab-firmware/issues/643
#
# Usage:
#   sudo ./can_setup.sh          # bring up
#   sudo ./can_setup.sh down     # bring down
#   sudo ./can_setup.sh verify   # candump one-shot check (Ctrl-C to stop)
#
# VESCs on bus: CAN ID 61 (0x3D) and CAN ID 79 (0x4F), 500 kbps
set -euo pipefail

IFACE="${CAN_IFACE:-can0}"
BITRATE="${CAN_BITRATE:-500000}"

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

cmd="${1:-up}"

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..."
    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)
    log "Listening on $IFACE — expecting frames from VESC IDs 0x3D (61) and 0x4F (79)"
    log "Press Ctrl-C to stop."
    exec candump "$IFACE"
    ;;

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