#!/usr/bin/env bash
# TrainerDay — ANT+ USB stick setup for Linux
#
# Installs a udev rule so TrainerDay can communicate with your Garmin / Dynastream
# ANT+ USB stick. Without this rule, the kernel claims the stick as a serial device
# (usb_serial_simple) and TrainerDay can't talk to it. One-time setup, requires sudo.
#
# Usage:
#   curl -fsSL https://download.trainerday.com/linux/setup-antplus.sh | sudo bash

set -euo pipefail

RULE_FILE="/etc/udev/rules.d/99-trainerday-ant.rules"

bold() { printf "\033[1m%s\033[0m\n" "$1"; }
info() { printf "  %s\n" "$1"; }
warn() { printf "\033[33m  %s\033[0m\n" "$1"; }
err()  { printf "\033[31m  %s\033[0m\n" "$1" >&2; }

[[ "$(uname -s)" == "Linux" ]] || { err "This setup is for Linux only."; exit 1; }

if [[ $EUID -ne 0 ]]; then
  err "This script must be run as root (it writes to /etc/udev/rules.d/)."
  err "Re-run with sudo:"
  err "  curl -fsSL https://download.trainerday.com/linux/setup-antplus.sh | sudo bash"
  exit 1
fi

bold "Installing ANT+ udev rule..."

cat > "$RULE_FILE" <<'EOF'
# TrainerDay — Garmin / Dynastream ANT+ USB sticks
# Grants non-root access so TrainerDay (libusb) can claim the device and detach
# the kernel's usb_serial_simple driver at runtime.
#   0x0fcf:0x1008 = GarminStick2
#   0x0fcf:0x1009 = GarminStick3 / "ANT USB-m"
SUBSYSTEM=="usb", ATTR{idVendor}=="0fcf", ATTR{idProduct}=="1008", MODE="0666"
SUBSYSTEM=="usb", ATTR{idVendor}=="0fcf", ATTR{idProduct}=="1009", MODE="0666"
EOF

info "Wrote $RULE_FILE"

info "Reloading udev rules..."
udevadm control --reload-rules
udevadm trigger --subsystem-match=usb

bold ""
bold "Done."
info "The new permissions are applied to any ANT+ stick already plugged in —"
info "no need to unplug it. Launch TrainerDay and your stick should appear"
info "in the device list."
