#!/bin/bash
#
# Purpose : Find the radios plugged into this computer's USB: each one's CAT
#           serial port, its sound card, and what model it is
#
# Usage   : radio [detect] [--probe]
#           radio probe PORT
#           radio help

SELF="$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")"
# shellcheck source=lib.sh
source "$SELF/lib.sh"

RADIOS_CONF="${HAMPACK_RADIOS_CONF:-$SELF/radios.conf}"
# Where to look for devices. Tests point these at fake trees
SYSFS="${RADIO_SYSFS:-/sys}"
DEVDIR="${RADIO_DEV:-/dev}"
PROC="${RADIO_PROC:-/proc}"
LOCKDIR="${RADIO_LOCKDIR:-/run/lock}"
# CAT baud rates to try, most likely first
BAUDS=(38400 115200 19200 9600 4800)

usage() {
  cat << EOF
Usage: radio [detect] [--probe]
       radio probe PORT

  detect          List the radios plugged into USB: each one's serial port,
                  its sound card and, if radio recognises it, its model.
                  Doesn't send the radios anything
  detect --probe  Also ask radios it doesn't recognise what they are, over each
                  serial port that no other program is using
  probe PORT      Ask the radio on serial port PORT what it is
EOF
}

# Print a sysfs attribute, or nothing if the device hasn't got it
attr() {
  [ -r "$1/$2" ] && printf '%s' "$(< "$1/$2")"
  return 0
}

# Print the USB device (the sysfs directory with idVendor) a device belongs to
usb_device() {
  local d
  d="$(readlink -f "$1")" || return 1
  while [ "$d" != / ] && [ -n "$d" ]; do
    [ -f "$d/idVendor" ] && { echo "$d"; return 0; }
    d="$(dirname "$d")"
  done
  return 1
}

# Find the USB serial ports and USB sound cards: PORT_USB[ttyUSB0] and
# CARD_USB[card1] are the USB devices they belong to
find_devices() {
  declare -gA PORT_USB=() CARD_USB=()
  local t c dev
  for t in "$SYSFS"/class/tty/tty{USB,ACM}*; do
    [ -e "$t/device" ] && dev="$(usb_device "$t/device")" && PORT_USB["${t##*/}"]="$dev"
  done
  for c in "$SYSFS"/class/sound/card*; do
    [ -e "$c/device" ] && dev="$(usb_device "$c/device")" && CARD_USB["${c##*/}"]="$dev"
  done
  return 0
}

has_ports() {
  local p
  for p in "${!PORT_USB[@]}"; do [ "${PORT_USB[$p]}" = "$1" ] && return 0; done
  return 1
}

has_card() {
  local c
  for c in "${!CARD_USB[@]}"; do [ "${CARD_USB[$c]}" = "$1" ] && return 0; done
  return 1
}

# Print the radio a USB serial device belongs to. A radio's serial chip and sound
# card are either one USB device or two behind the radio's own hub, so: the
# device itself if it has a sound card too, or its hub if that holds one sound
# card and nothing but serial devices, or else just the device. Nothing tells
# a radio's hub from a hub you've plugged a serial cable and a sound card into.
radio_of() {
  local dev="$1" hub child cards=0
  hub="$(dirname "$dev")"
  if ! has_card "$dev" && [[ "${hub##*/}" != usb* ]] && [ -f "$hub/idVendor" ]; then
    for child in "$hub"/*/; do
      child="${child%/}"
      [ -f "$child/idVendor" ] || continue
      if has_card "$child"; then
        cards=$((cards + 1))
      elif ! has_ports "$child"; then
        cards=99  # something else is on this hub
      fi
    done
    (( cards == 1 )) && { echo "$hub"; return; }
  fi
  echo "$dev"
}

# Print the radio's sound card, as card1
card_of() {
  local c
  for c in $(printf '%s\n' "${!CARD_USB[@]}" | sort -V); do
    [ "${CARD_USB[$c]}" = "$1" ] || [ "$(dirname "${CARD_USB[$c]}")" = "$1" ] && { echo "$c"; return; }
  done
}

# Print the port's stable name in /dev/serial/by-id, or its /dev name if it has none
port_path() {
  local link
  for link in "$DEVDIR"/serial/by-id/*; do
    [ -L "$link" ] && [ "$(basename "$(readlink -f "$link")")" = "$1" ] && { echo "/dev/serial/by-id/${link##*/}"; return; }
  done
  echo "/dev/$1"
}

# Print the radios in radios.conf whose field matches: matching FIELD VALUE.
# usb_serial= is a pattern; the others must be equal (ignoring case)
matching() {
  MATCH_FIELD="$1" MATCH_VALUE="$2" MATCHES=()
  parse_conf "$RADIOS_CONF" match_radio
  [ ${#MATCHES[@]} -gt 0 ] && printf '%s\n' "${MATCHES[@]}"
}
match_radio() {
  local want="${CONF[$MATCH_FIELD]}"
  [ -n "$want" ] || return 0
  if [ "$MATCH_FIELD" = usb_serial ]; then
    # shellcheck disable=SC2053  # want is a pattern
    [[ "$MATCH_VALUE" == $want ]] || return 0
  else
    [ "${want,,}" = "${MATCH_VALUE,,}" ] || return 0
  fi
  MATCHES+=("${CONF[_name]} (Hamlib model ${CONF[hamlib]})")
}

# Print why a port can't be probed, or nothing if it can
cant_probe() {
  local port="$1" dev fd pid group
  dev="$(readlink -f "$port")"
  if [ ! -e "$port" ]; then
    echo "$port doesn't exist"
  elif [ ! -r "$port" ] || [ ! -w "$port" ]; then
    group="$(stat -c %G "$dev")"
    if id -nG "$USER" | tr ' ' '\n' | grep -qx "$group"; then
      echo "you can't open $port yet: log out and back in, so you're in the $group group"
    else
      echo "you can't open $port: add yourself to the $group group with \`sudo usermod -aG $group $USER\`, then log out and back in"
    fi
  elif [ -e "$LOCKDIR/LCK..${dev##*/}" ]; then
    echo "$port is locked by another program ($LOCKDIR/LCK..${dev##*/})"
  else
    for fd in "$PROC"/[0-9]*/fd/*; do
      [ "$(readlink "$fd" 2> /dev/null)" = "$dev" ] || continue
      pid="${fd#"$PROC"/}"
      pid="${pid%%/*}"
      echo "$port is in use by $(cat "$PROC/$pid/comm" 2> /dev/null || echo "another program") (process $pid)"
      return
    done
  fi
}

# Ask the radio on PORT what it is, at each baud rate in turn: the Kenwood-style
# ID; (Kenwood, Yaesu, Elecraft) and Icom's CI-V "read transceiver ID". Prints
# "BAUD cat_id DIGITS" or "BAUD civ ADDRESS" for the first answer. DTR and RTS
# are dropped as soon as the port opens, since many interfaces key the
# transmitter with one of them; the port opening still raises them for a moment.
ask_radio() {
  python3 -I -c '
import fcntl, os, re, select, struct, sys, termios, time

def unkey():
    try:
        fcntl.ioctl(fd, termios.TIOCMBIC, struct.pack("I", termios.TIOCM_DTR | termios.TIOCM_RTS))
    except OSError:
        pass  # not a real serial port

def ask(command, wait=0.4):
    termios.tcflush(fd, termios.TCIOFLUSH)
    os.write(fd, command)
    reply, end = b"", time.monotonic() + wait
    while (left := end - time.monotonic()) > 0:
        if not select.select([fd], [], [], left)[0]:
            break
        try:
            chunk = os.read(fd, 256)
        except BlockingIOError:
            continue
        if not chunk:
            break
        reply += chunk
    return reply

try:
    fd = os.open(sys.argv[1], os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK)
except OSError as e:
    print("error", e.strerror)
    sys.exit(1)
unkey()
for baud in sys.argv[2:]:
    attrs = termios.tcgetattr(fd)
    speed = getattr(termios, "B" + baud)
    # Raw 8N1, no flow control
    attrs[0:6] = [0, 0, termios.CS8 | termios.CREAD | termios.CLOCAL, 0, speed, speed]
    attrs[6][termios.VMIN] = attrs[6][termios.VTIME] = 0
    termios.tcsetattr(fd, termios.TCSANOW, attrs)
    unkey()
    found = re.search(rb"ID(\d{3,4});", ask(b"ID;"))
    if found:
        print(baud, "cat_id", found.group(1).decode())
        break
    # To any address (00) from a computer (E0); the radio answers to E0 from its address
    found = re.search(rb"\xfe\xfe\xe0(.)\x19\x00.\xfd", ask(bytes.fromhex("fefe00e01900fd")), re.S)
    if found:
        print(baud, "civ", found.group(1).hex().upper())
        break
' "$1" "${BAUDS[@]}"
}

# Probe PORT and set ANSWER_BAUD, ANSWER_FIELD and ANSWER_VALUE from its
# answer, or PROBE_ERROR if the port couldn't be opened
probe_port() {
  local reply
  ANSWER_BAUD="" ANSWER_FIELD="" ANSWER_VALUE="" PROBE_ERROR=""
  if ! reply="$(ask_radio "$1")"; then
    PROBE_ERROR="${reply#error }"
    PROBE_ERROR="${PROBE_ERROR:-python3 failed}"
    return 1
  fi
  read -r ANSWER_BAUD ANSWER_FIELD ANSWER_VALUE <<< "$reply"
  [ -n "$ANSWER_VALUE" ]
}

# Join the radios matching prints into one line
one_of() {
  if [ "$(wc -l <<< "$1")" -eq 1 ]; then
    echo "$1"
  else
    echo "one of: $(paste -sd '|' <<< "$1" | sed 's/|/, /g')"
  fi
}

# Describe the radio that answered
describe_answer() {
  local models
  models="$(matching "$ANSWER_FIELD" "$ANSWER_VALUE")"
  if [ -z "$models" ]; then
    if [ "$ANSWER_FIELD" = civ ]; then
      echo "an Icom radio at CI-V address $ANSWER_VALUE that radio doesn't know"
    else
      echo "a radio that answered ID$ANSWER_VALUE; that radio doesn't know"
    fi
  else
    one_of "$models"
  fi
}

# radio detect: list each radio and what's known about it
detect() {
  local probe=0 radio port dev card name serial reason found=0
  [ "${1:-}" = --probe ] && probe=1
  [ "${1:-}" = --probe ] || [ -z "${1:-}" ] || { usage >&2; return 2; }

  find_devices
  if [ ${#PORT_USB[@]} -eq 0 ]; then
    echo "No USB serial ports found: is the radio plugged in and switched on?"
    return 1
  fi

  # Group the ports by radio
  declare -A RADIO_PORTS=()
  for port in $(printf '%s\n' "${!PORT_USB[@]}" | sort -V); do
    radio="$(radio_of "${PORT_USB[$port]}")"
    RADIO_PORTS["$radio"]+="$port "
  done

  for radio in $(printf '%s\n' "${!RADIO_PORTS[@]}" | sort); do
    (( found++ )) && echo
    local ports=() usb_devs=() models="" how="" cat_port="" lines=()
    read -ra ports <<< "${RADIO_PORTS[$radio]}"

    # Recognise it by its USB serial number, or else by asking it
    for port in "${ports[@]}"; do
      dev="${PORT_USB[$port]}"
      [[ " ${usb_devs[*]} " == *" $dev "* ]] || usb_devs+=("$dev")
    done
    for dev in "${usb_devs[@]}"; do
      serial="$(attr "$dev" serial)"
      [ -n "$serial" ] && models="$(matching usb_serial "$serial")" && break
    done
    [ -n "$models" ] && models="$(one_of "$models")" && how="recognised by its USB serial number"

    if [ -z "$models" ] && (( probe )); then
      for port in "${ports[@]}"; do
        reason="$(cant_probe "$DEVDIR/$port")"
        if [ -n "$reason" ]; then
          lines+=("  Couldn't ask on $port: $reason")
        elif probe_port "$DEVDIR/$port"; then
          models="$(describe_answer)"
          how="answered on $port at $ANSWER_BAUD baud"
          cat_port="$port"
          break
        elif [ -n "$PROBE_ERROR" ]; then
          lines+=("  Couldn't ask on $port: $PROBE_ERROR")
        fi
      done
    fi

    if [ -z "$models" ]; then
      echo "Unknown radio or interface"
    else
      echo "${models^}, $how"
    fi

    for port in "${ports[@]}"; do
      if [ "$port" = "$cat_port" ]; then
        name="CAT port:   "
      else
        name="Serial port:"
      fi
      echo "  $name $(port_path "$port")"
    done
    card="$(card_of "$radio")"
    if [ -n "$card" ]; then
      echo "  Sound card:  hw:CARD=$(attr "$SYSFS/class/sound/$card" id) ($card)"
    else
      echo "  Sound card:  none found with it"
    fi
    for dev in "${usb_devs[@]}"; do
      serial="$(attr "$dev" serial)"
      echo "  USB:         $(attr "$dev" idVendor):$(attr "$dev" idProduct) $(attr "$dev" manufacturer) $(attr "$dev" product)${serial:+, serial $serial}"
    done
    [ ${#lines[@]} -eq 0 ] || printf '%s\n' "${lines[@]}"

    if [ -z "$models" ]; then
      if (( probe )); then
        [ ${#lines[@]} -eq ${#ports[@]} ] ||
          echo "  Nothing answered. If it's a radio, check it's switched on and its CAT rate is one of ${BAUDS[*]} baud. Interfaces like the Digirig answer only for a radio behind them"
      else
        echo "  Run \`radio detect --probe\` to ask it what it is"
      fi
    fi
  done
}

# radio probe PORT: ask one port
probe() {
  local port="${1:-}" reason
  [ -n "$port" ] || { usage >&2; return 2; }
  reason="$(cant_probe "$port")"
  [ -z "$reason" ] || { echo "Can't ask: $reason" >&2; return 1; }
  if probe_port "$port"; then
    echo "$(describe_answer), at $ANSWER_BAUD baud"
  elif [ -n "$PROBE_ERROR" ]; then
    echo "Can't ask: $PROBE_ERROR" >&2
    return 1
  else
    echo "Nothing answered on $port at ${BAUDS[*]} baud"
    return 1
  fi
}

case "${1:-detect}" in
  detect) shift; detect "$@" ;;
  probe) shift; probe "$@" ;;
  help | -h | --help) usage ;;
  --probe) detect --probe ;;
  *) usage >&2; exit 2 ;;
esac
