#!/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. Then set up
#           rigctld for one, and point HamPack's programs at it
#
# Usage   : radio [detect] [--probe]
#           radio probe PORT
#           radio configure [--force] [--model N] [--flrig] [--no-cat --ptt HOW] [NUMBER]
#           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)

CONFIG_HOME="${XDG_CONFIG_HOME:-$HOME/.config}"
RIGCTLD_UNIT="$CONFIG_HOME/systemd/user/hampack-rigctld.service"
RIGCTLD_ADDR=127.0.0.1:4532
WSJTX_FLATPAK=io.sourceforge.wsjt.wsjtx
WSJTX_CONF="$HOME/.var/app/$WSJTX_FLATPAK/config/WSJT-X.ini"
JS8CALL_CONF="$CONFIG_HOME/JS8Call.ini"
PAT_CONF="$CONFIG_HOME/pat/config.json"
FLDIGI_CONF="$HOME/.fldigi/fldigi_def.xml"
NOT1MM_CONF="$CONFIG_HOME/not1mm/not1mm.json"
QLOG_FLATPAK=io.github.foldynl.QLog
QLOG_DB="$HOME/.var/app/$QLOG_FLATPAK/data/hamradio/QLog/qlog.db"
POTACAT_DIR="$CONFIG_HOME/potacat"
GRAYWOLF_DB="$HOME/.local/share/graywolf/graywolf.db"
FLRIG_DIR="$HOME/.flrig"
AUTOSTART_DIR="$CONFIG_HOME/autostart"
FLRIG_AUTOSTART="$AUTOSTART_DIR/hampack-flrig.desktop"
# flrig's baud rates; it saves the rate as its place in this list
FLRIG_BAUDS=(300 600 1200 2400 4800 9600 19200 38400 57600 115200 230400 460800)
DIREWOLF_CONF="$HAMPACK_STATE/conf.d/direwolf.conf"
# What HamPack's conf.d/direwolf.conf ships with, which configure replaces
DIREWOLF_DEFAULT_ADEVICE="plughw:0,0"
DIREWOLF_DEFAULT_PTT="CM108"
# WSJT-X and JS8Call save PTT_method_CAT like this: a Qt variant holding the
# enum's name. The bytes before each name are its length, with the NUL
PTT_CAT='@Variant(\0\0\0\x7f\0\0\0\x1eTransceiverFactory::PTTMethod\0\0\0\0\xfPTT_method_CAT\0)'

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
  configure       Set up the radio (if there's more than one, give its number
                  from \`radio\`): run rigctld for it as a systemd user service,
                  and point WSJT-X, JS8Call, Pat, fldigi, Dire Wolf, not1mm,
                  QLog, POTACAT and Graywolf at rigctld. Only changes
                  settings you haven't set, and backs up each file it changes.
                  Quit those programs first
    --force       Replace rig settings you've set yourself
    --model N     Use Hamlib model N (\`rigctl -l\`), for a radio that radio
                  can't tell apart from others, or doesn't know
    --flrig       Put flrig in charge of the radio, with rigctld passing the
                  other programs through it. flrig then has to be running
                  for them to reach the radio
    --no-cat      For a radio with no CAT on an interface with a serial port
                  (a handheld on a Digirig): rigctld only keys it, so give
                  --ptt too. Sound cards with no serial port (an AIOC, a
                  SignaLink) are set up like this anyway
    --ptt HOW     How the interface keys the radio: cm108 (its sound card's
                  PTT pin), rts or dtr (its serial port's lines), or vox
                  (the radio keys itself on the audio). A sound card is
                  cm108 if it can be, and vox otherwise
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=() HIDRAW_USB=()
  local t c h 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
  for h in "$SYSFS"/class/hidraw/hidraw*; do
    [ -e "$h/device" ] && dev="$(usb_device "$h/device")" && HIDRAW_USB["${h##*/}"]="$dev"
  done
  return 0
}

# Whether a USB device is a CM108-family sound card, whose GPIO pin can key a
# radio: the devices Dire Wolf 1.8 treats as CM108-compatible, as
# udev/70-hampack-cm108.rules does. cm108_compatible USB_DEVICE
cm108_compatible() {
  case "$(attr "$1" idVendor):$(attr "$1" idProduct)" in
    0d8c:000[89a-f] | 0d8c:0012 | 0d8c:0013 | 0d8c:0139 | 0d8c:013a | 0d8c:013c) return 0 ;;
    0c76:1605 | 0c76:1607 | 0c76:160b) return 0 ;;
    1209:7388) return 0 ;;
    *) return 1 ;;
  esac
}

# Describe the CM108 PTT on a sound card's USB device, if it has one: the
# hidraw device it's keyed through, and whether you can open it
cm108_ptt() {
  local h
  cm108_compatible "$1" || return 1
  for h in $(printf '%s\n' "${!HIDRAW_USB[@]}" | sort -V); do
    [ "${HIDRAW_USB[$h]}" = "$1" ] || continue
    if [ -r "$DEVDIR/$h" ] && [ -w "$DEVDIR/$h" ]; then
      echo "/dev/$h"
    else
      echo "/dev/$h, which you can't open yet: \`update\` installs HamPack's udev rule for it, which lets whoever is at the desktop use it"
    fi
    return 0
  done
  echo "its GPIO pin, though its hidraw device is missing"
}

# Print the stable name of the hidraw device on a CM108 sound card's USB
# device: its link in /dev/input/by-id, unless another device has the same
# id (two cards of a kind, with no serial number), then its link in
# /dev/input/by-path, or else its /dev name. hidraw_path USB_DEVICE
hidraw_path() {
  local h="" other link same=0
  for other in $(printf '%s\n' "${!HIDRAW_USB[@]}" | sort -V); do
    [ "${HIDRAW_USB[$other]}" = "$1" ] && { h="$other"; break; }
  done
  [ -n "$h" ] || return 1
  for other in "${!HIDRAW_USB[@]}"; do
    [ "$other" != "$h" ] || continue
    [ "${HIDRAW_USB[$other]}" != "$1" ] || continue
    [ "$(attr "${HIDRAW_USB[$other]}" idVendor):$(attr "${HIDRAW_USB[$other]}" idProduct):$(attr "${HIDRAW_USB[$other]}" serial)" = \
      "$(attr "$1" idVendor):$(attr "$1" idProduct):$(attr "$1" serial)" ] && same=1
  done
  for link in $( ((same)) || echo "$DEVDIR"/input/by-id/*-hidraw) "$DEVDIR"/input/by-path/*-hidraw; do
    [ -L "$link" ] && [ "$(basename "$(readlink -f "$link")")" = "$h" ] && { echo "/dev/${link#"$DEVDIR"/}"; return 0; }
  done
  echo "/dev/$h"
}

# Whether a sound card can both play and record, as an interface to a radio
# must: not a webcam's microphone, say
plays_and_records() {
  local n="${1#card}" p c
  for p in "$SYSFS"/class/sound/pcmC"${n}"D*p; do
    [ -e "$p" ] || continue
    for c in "$SYSFS"/class/sound/pcmC"${n}"D*c; do
      [ -e "$c" ] && return 0
    done
  done
  return 1
}

# Print the USB sound cards that no serial port goes with, as interfaces to
# a radio with no CAT control: "CARD USB_DEVICE", one to a line
sound_only_cards() {
  local card radio paired=" "
  for radio in "${RADIOS[@]}"; do
    paired+="$(card_of "$radio") "
  done
  for card in $(printf '%s\n' "${!CARD_USB[@]}" | sort -V); do
    [[ "$paired" == *" $card "* ]] && continue
    plays_and_records "$card" && echo "$card ${CARD_USB[$card]}"
  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, as NAME|HAMLIB, one to
# a line: 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]}|${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:
        # Elecraft radios all answer ID017;. Their option modules (OM;) tell
        # them apart: twelve characters, which radio reads
        options = ""
        if found.group(1) == b"017":
            om = re.search(rb"OM ([A-Za-z0-9-]{12});", ask(b"OM;"))
            options = om.group(1).decode() if om else ""
        print(baud, "cat_id", found.group(1).decode(), options)
        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="" ANSWER_OPTIONS="" 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 ANSWER_OPTIONS <<< "$reply"
  [ -n "$ANSWER_VALUE" ]
}

# Which Elecraft radio's option modules these are (its reply to OM;, after
# "OM "), as Hamlib 4.7's elecraft_open() reads them: a KX2 or KX3 has 0 and
# its model number (1 or 2) last; a K4 has S and 4 among them; a K3S has R;
# anything else is a K3. elecraft_model OPTIONS
elecraft_model() {
  if [ "${1:10:1}" = 0 ]; then
    case "${1:11:1}" in
      1) echo KX2 ;;
      2) echo KX3 ;;
      *) return 1 ;;
    esac
  elif [[ "$1" == *S* && "$1" == *4* ]]; then
    echo K4
  elif [[ "$1" == *R* ]]; then
    echo K3S
  else
    echo K3
  fi
}

# The radios that could have given the probe's answer, as matching prints
# them: those with its ID, narrowed by an Elecraft radio's option modules
answer_models() {
  local models model kind narrowed=""
  models="$(matching "$ANSWER_FIELD" "$ANSWER_VALUE")" || return 1
  if [ -n "${ANSWER_OPTIONS:-}" ] && kind="$(elecraft_model "$ANSWER_OPTIONS")"; then
    while IFS= read -r model; do
      [ "$(conf_field "${model%|*}" elecraft)" = "$kind" ] && narrowed+="$model"$'\n'
    done <<< "$models"
    [ -z "$narrowed" ] || models="${narrowed%$'\n'}"
  fi
  echo "$models"
}

# Describe the radios matching prints, in one line
models_text() {
  local line names=()
  while IFS= read -r line; do
    names+=("${line%|*} (Hamlib model ${line##*|})")
  done <<< "$1"
  if [ ${#names[@]} -eq 1 ]; then
    echo "${names[0]}"
  else
    local IFS='|'
    line="${names[*]}"
    echo "one of: ${line//|/, }"
  fi
}

# Describe a radio that answered, but that radios.conf doesn't know
unknown_answer_text() {
  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
}

# Describe the radio that answered
describe_answer() {
  local models
  models="$(answer_models)"
  if [ -n "$models" ]; then models_text "$models"; else unknown_answer_text; fi
}

# Find the radios: RADIOS lists them (the USB device or hub each is), and
# RADIO_PORTS[radio] its serial ports
find_radios() {
  local port radio
  declare -gA RADIO_PORTS=()
  RADIOS=()
  find_devices
  for port in $(printf '%s\n' "${!PORT_USB[@]}" | sort -V); do
    radio="$(radio_of "${PORT_USB[$port]}")"
    RADIO_PORTS["$radio"]+="$port "
  done
  mapfile -t RADIOS < <(printf '%s\n' "${!RADIO_PORTS[@]}" | sort | grep .)
  [ ${#RADIOS[@]} -gt 0 ]
}

# Work out what a radio is: identify RADIO WHEN, where WHEN says when to ask
# it: never, unknown (only if its USB serial number doesn't say) or always
# (to find its CAT port and baud rate). Sets:
#   ID_PORTS, ID_USB  its serial ports, and the USB devices they're on
#   ID_MODELS         the radios it could be, as matching prints them
#   ID_HOW            how it was recognised
#   ID_CAT_PORT, ID_BAUD  the port and baud rate it answered on
#   ID_ANSWER         what it answered, if radios.conf doesn't know it
#   ID_NOTES          ports it couldn't be asked on, and why
#   ID_ASKED          1 if any port could be asked
identify() {
  local radio="$1" when="$2" port dev serial reason
  ID_PORTS=() ID_USB=() ID_MODELS="" ID_HOW="" ID_CAT_PORT="" ID_BAUD="" ID_ANSWER="" ID_NOTES=() ID_ASKED=0
  read -ra ID_PORTS <<< "${RADIO_PORTS[$radio]}"
  for port in "${ID_PORTS[@]}"; do
    dev="${PORT_USB[$port]}"
    [[ " ${ID_USB[*]} " == *" $dev "* ]] || ID_USB+=("$dev")
  done

  for dev in "${ID_USB[@]}"; do
    serial="$(attr "$dev" serial)"
    [ -n "$serial" ] && ID_MODELS="$(matching usb_serial "$serial")" && break
  done
  [ -z "$ID_MODELS" ] || ID_HOW="recognised by its USB serial number"

  [ "$when" = always ] || { [ "$when" = unknown ] && [ -z "$ID_MODELS" ]; } || return 0
  for port in "${ID_PORTS[@]}"; do
    reason="$(cant_probe "$DEVDIR/$port")"
    if [ -n "$reason" ]; then
      ID_NOTES+=("Couldn't ask on $port: $reason")
      continue
    fi
    ID_ASKED=1
    if probe_port "$DEVDIR/$port"; then
      ID_CAT_PORT="$port" ID_BAUD="$ANSWER_BAUD"
      if [ -z "$ID_MODELS" ]; then
        ID_MODELS="$(answer_models)"
        [ -n "$ID_MODELS" ] || ID_ANSWER="$(unknown_answer_text)"
        ID_HOW="answered on $port at $ANSWER_BAUD baud"
      fi
      return 0
    elif [ -n "$PROBE_ERROR" ]; then
      ID_NOTES+=("Couldn't ask on $port: $PROBE_ERROR")
    fi
  done
}

# Print the radio's sound card as ALSA names it (hw:CARD=CODEC), or nothing
card_name() {
  local card
  card="$(card_of "$1")"
  [ -z "$card" ] || echo "hw:CARD=$(attr "$SYSFS/class/sound/$card" id)"
}

# radio detect: list each radio and what's known about it
detect() {
  local when=never radio port name card dev serial n=0
  case "${1:-}" in
    --probe) when=unknown ;;
    "") ;;
    *) usage >&2; return 2 ;;
  esac

  local sound_only
  find_radios
  sound_only="$(sound_only_cards)"
  if [ ${#RADIOS[@]} -eq 0 ] && [ -z "$sound_only" ]; then
    echo "No USB serial ports found: is the radio plugged in and switched on?"
    return 1
  fi

  for radio in "${RADIOS[@]}"; do
    (( n++ )) && echo
    identify "$radio" "$when"
    if [ -n "$ID_MODELS" ]; then
      name="$(models_text "$ID_MODELS")"
      echo "$n. ${name^}, $ID_HOW"
    elif [ -n "$ID_ANSWER" ]; then
      echo "$n. ${ID_ANSWER^}, $ID_HOW"
    else
      echo "$n. Unknown radio or interface"
    fi

    for port in "${ID_PORTS[@]}"; do
      if [ "$port" = "$ID_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:  $(card_name "$radio") ($card)"
      name="$(cm108_ptt "${CARD_USB[$card]}")" && echo "  CM108 PTT:   $name"
    else
      echo "  Sound card:  none found with it"
    fi
    for dev in "${ID_USB[@]}"; do
      serial="$(attr "$dev" serial)"
      echo "  USB:         $(attr "$dev" idVendor):$(attr "$dev" idProduct) $(attr "$dev" manufacturer) $(attr "$dev" product)${serial:+, serial $serial}"
    done
    [ ${#ID_NOTES[@]} -eq 0 ] || printf '  %s\n' "${ID_NOTES[@]}"

    if [ -z "$ID_MODELS$ID_ANSWER" ]; then
      if [ "$when" = never ]; then
        echo "  Run \`radio detect --probe\` to ask it what it is"
      elif (( ID_ASKED )); then
        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"
      fi
    fi
  done

  [ -n "$sound_only" ] || return 0
  (( n == 0 )) || echo
  echo "USB sound cards with no serial port, for a radio keyed by VOX or a PTT line:"
  local id ptt
  while read -r card dev; do
    id="$(attr "$SYSFS/class/sound/$card" id)"
    ptt="$(cm108_ptt "$dev")" && ptt="PTT through CM108 on $ptt" || ptt="PTT by VOX, or a line of its own"
    echo "$((++n)). hw:CARD=$id ($card): $(attr "$dev" manufacturer) $(attr "$dev" product), $(attr "$dev" idVendor):$(attr "$dev" idProduct). $ptt"
  done <<< "$sound_only"
}

# 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
}

# Print a key's value from a section of an INI file: ini_get FILE SECTION KEY
ini_get() {
  [ -f "$1" ] || return 0
  S="$2" K="$3" awk '
    /^\[/ { in_section = ($0 == "[" ENVIRON["S"] "]"); next }
    in_section && index($0, ENVIRON["K"] "=") == 1 { print substr($0, length(ENVIRON["K"]) + 2); exit }
  ' "$1"
}

# Set a key in a section of an INI file, adding the section (and the file) if
# need be: ini_set FILE SECTION KEY VALUE. Values are written as they are, so
# Qt's escapes (\0, \x7f) stay as Qt wrote them
ini_set() {
  local tmp
  mkdir -p "$(dirname "$1")" && touch "$1" && tmp="$(mktemp "$1.XXXXXX")" || return 1
  S="$2" K="$3" V="$4" awk '
    function put() { print ENVIRON["K"] "=" ENVIRON["V"]; done = 1 }
    /^\[/ {
      if (in_section && !done) put()
      in_section = ($0 == "[" ENVIRON["S"] "]")
      if (in_section) found = 1
      print
      next
    }
    in_section && index($0, ENVIRON["K"] "=") == 1 { if (!done) put(); next }
    { print }
    END {
      if (in_section && !done) put()
      if (!found) { if (NR) print ""; print "[" ENVIRON["S"] "]"; put() }
    }
  ' "$1" > "$tmp" && chmod --reference="$1" "$tmp" && mv -f "$tmp" "$1"
}

# Copy a file before changing it, and say so
back_up() {
  [ -f "$1" ] || return 0
  local copy
  copy="$1.bak-$(date +%Y%m%d-%H%M%S)"
  cp -p "$1" "$copy" && BACKUPS+=("$copy")
}

# Say what happened to one program: report NAME MESSAGE
report() {
  printf '  %-10s %s\n' "$1:" "$2"
}

running() {
  pgrep -x "$1" > /dev/null 2>&1
}

# Print a string as Qt writes it to an INI file: quoted if it has characters
# Qt would read otherwise (a comma makes a list), with \ and " escaped
qt_ini_string() {
  local v="${1//\\/\\\\}"
  v="${v//\"/\\\"}"
  if [[ "$1" =~ [,\;=\"\\] ]] || [[ "$1" == " "* ]] || [[ "$1" == *" " ]]; then
    printf '"%s"\n' "$v"
  else
    printf '%s\n' "$1"
  fi
}

# Find the radio's sound card in PipeWire, as programs that use it (through
# Qt) name it: find_pipewire_nodes CARD_NUMBER sets PW_IN_NAME and
# PW_OUT_NAME (node names, such as alsa_input.usb-...) and PW_IN_DESC and
# PW_OUT_DESC (as PipeWire describes them)
find_pipewire_nodes() {
  PW_IN_NAME="" PW_IN_DESC="" PW_OUT_NAME="" PW_OUT_DESC=""
  [ -n "$1" ] && command -v pactl > /dev/null || return 1
  # shellcheck disable=SC2016  # $n is jq's
  local query='first(.[] | select(.properties["alsa.card"] == $n and .properties["device.class"] == "sound")) | [.name, .description] | @tsv'
  IFS=$'\t' read -r PW_IN_NAME PW_IN_DESC < <(pactl -f json list sources 2> /dev/null | jq -r --arg n "$1" "$query" 2> /dev/null)
  IFS=$'\t' read -r PW_OUT_NAME PW_OUT_DESC < <(pactl -f json list sinks 2> /dev/null | jq -r --arg n "$1" "$query" 2> /dev/null)
  [ -n "$PW_IN_NAME" ] && [ -n "$PW_OUT_NAME" ] || { PW_IN_NAME="" PW_OUT_NAME=""; return 1; }
}

# A sound device setting that names no particular card: unset, or a default
is_default_device() {
  case "$1" in
    "" | default | pipewire | pulse | sysdefault) return 0 ;;
    *) return 1 ;;
  esac
}

# Say what was set, and what was left alone and why: say_changes NAME, from
# SAID (what was set) and LEFT (what was left alone)
say_changes() {
  local message="" IFS='|'
  if [ ${#SAID[@]} -gt 0 ]; then
    message="${SAID[*]}"
    message="${message//|/, }"
  fi
  if [ ${#LEFT[@]} -gt 0 ]; then
    local left="${LEFT[*]}"
    message="${message:+$message. }Left ${left//|/ and } alone: \`radio configure --force\` replaces $( [ ${#LEFT[@]} -eq 1 ] && echo it || echo them)"
  fi
  report "$1" "${message:-already set up}"
}

# WSJT-X and JS8Call share their settings: point one at rigctld, with PTT by
# CAT, and at the radio's sound card in PipeWire. WSJT-X keeps the device's
# name in SoundInName; JS8Call keeps it in SoundInId, and its description in
# SoundInName. configure_qt_app NAME FILE PROCESS wsjtx|js8call
configure_qt_app() {
  local name="$1" file="$2" kind="$4" rig net in_key=SoundInName out_key=SoundOutName current_in current_out i
  local keys=() values=()
  SAID=() LEFT=()
  if running "$3"; then
    report "$name" "skipped, because it's running and would overwrite its settings when it quits. Quit it and run \`radio configure\` again"
    return
  fi

  rig="$(ini_get "$file" Configuration Rig)"
  net="$(ini_get "$file" Configuration CATNetworkPort)"
  if [ "$rig" = "Hamlib NET rigctl" ] && [ "$net" = "$RIGCTLD_ADDR" ]; then
    :
  elif [ -z "$rig" ] || [ "$rig" = None ] || (( FORCE )); then
    keys+=(Rig CATNetworkPort PTTMethod)
    values+=("Hamlib NET rigctl" "$RIGCTLD_ADDR" "$PTT_CAT")
    SAID+=("rig control through rigctld, PTT by CAT")
  else
    LEFT+=("its rig ($rig)")
  fi

  if [ -n "$PW_IN_NAME" ]; then
    [ "$kind" = wsjtx ] || { in_key=SoundInId out_key=SoundOutId; }
    current_in="$(ini_get "$file" Configuration "$in_key")"
    current_out="$(ini_get "$file" Configuration "$out_key")"
    if [ "$current_in" = "$PW_IN_NAME" ] && [ "$current_out" = "$PW_OUT_NAME" ]; then
      :
    elif { is_default_device "$current_in" && is_default_device "$current_out"; } || (( FORCE )); then
      keys+=("$in_key" "$out_key")
      values+=("$PW_IN_NAME" "$PW_OUT_NAME")
      if [ "$kind" = js8call ]; then
        keys+=(SoundInName SoundOutName)
        values+=("$(qt_ini_string "$PW_IN_DESC")" "$(qt_ini_string "$PW_OUT_DESC")")
      fi
      SAID+=("sound card \"$PW_OUT_DESC\"")
    else
      LEFT+=("its sound card (${current_in:-$current_out})")
    fi
  fi

  if [ ${#keys[@]} -gt 0 ]; then
    back_up "$file"
    for i in "${!keys[@]}"; do
      ini_set "$file" Configuration "${keys[i]}" "${values[i]}" || { report "$name" "couldn't change $file"; return 1; }
    done
  fi
  say_changes "$name"
}

# Print a value from an FLTK preferences file, as flrig keeps its settings:
# fltk_get FILE KEY. A long value carries on in lines that start with +
fltk_get() {
  [ -f "$1" ] || return 0
  K="$2" awk '
    found && /^\+/ { value = value substr($0, 2); next }
    found { exit }
    index($0, ENVIRON["K"] ":") == 1 { value = substr($0, length(ENVIRON["K"]) + 2); found = 1 }
    END { if (found) print value }
  ' "$1"
}

# Set a value in an FLTK preferences file, making the file if need be:
# fltk_set FILE APPLICATION KEY VALUE. Values are written as FLTK writes them:
# 60 characters on the key's line, then 80 a line on lines starting with +
fltk_set() {
  local tmp
  mkdir -p "$(dirname "$1")" || return 1
  [ -f "$1" ] || printf '; FLTK preferences file format 1.0\n; vendor: w1hkj.com\n; application: %s\n\n[.]\n\n' "$2" > "$1" || return 1
  tmp="$(mktemp "$1.XXXXXX")" || return 1
  K="$3" V="$4" awk '
    function put(   v) {
      v = ENVIRON["V"]
      print ENVIRON["K"] ":" substr(v, 1, 60)
      for (v = substr(v, 61); v != ""; v = substr(v, 81)) print "+" substr(v, 1, 80)
      done = 1
    }
    skipping && /^\+/ { next }
    { skipping = 0 }
    index($0, ENVIRON["K"] ":") == 1 { skipping = 1; next }
    { print }
    $0 == "[.]" && !done { put() }
    END { if (!done) put() }
  ' "$1" > "$tmp" && chmod --reference="$1" "$tmp" && mv -f "$tmp" "$1"
}

# Print the autostart entries, other than HamPack's, that start flrig when
# you log in
other_flrig_autostarts() {
  local entry exec
  for entry in "$AUTOSTART_DIR"/*.desktop; do
    [ -f "$entry" ] && [ "$entry" != "$FLRIG_AUTOSTART" ] || continue
    grep -qix 'Hidden=true' "$entry" && continue
    exec="$(sed -n 's/^Exec=//p' "$entry" | head -1)"
    exec="${exec%% *}"
    [ "${exec##*/}" = flrig ] && echo "$entry"
  done
  return 0
}

# Start flrig when you log in, so rigctld has it to talk to: an autostart
# entry, marked as HamPack's so it's only ever removed by HamPack
add_flrig_autostart() {
  mkdir -p "$AUTOSTART_DIR" && cat > "$FLRIG_AUTOSTART" << 'EOF'
[Desktop Entry]
Type=Application
Name=flrig
Comment=Controls the radio, for rigctld and the programs that use it. Added by HamPack's radio configure --flrig
Exec=flrig
Icon=flrig
Terminal=false
X-GNOME-Autostart-enabled=true
X-HamPack=radio configure --flrig
EOF
}

# Remove HamPack's flrig autostart entry, if that's what it is. Prints
# whether it removed one
remove_flrig_autostart() {
  [ -f "$FLRIG_AUTOSTART" ] && grep -qx 'X-HamPack=radio configure --flrig' "$FLRIG_AUTOSTART" || return 1
  rm -f "$FLRIG_AUTOSTART"
}

# flrig can't reach a radio through rigctld, and the two can't both have its
# port open. With --flrig, flrig gets the radio, its port, baud rate and PTT
# by CAT, and rigctld (Hamlib's FLRig backend) passes everything to it;
# otherwise flrig is left alone. configure_flrig FLRIG_NAME PORT BAUD
configure_flrig() {
  local main="$FLRIG_DIR/flrig.prefs" rig="$FLRIG_DIR/$1.prefs" current_name current_port index i version
  if ! command -v flrig > /dev/null; then
    report flrig "not installed"
    return
  fi
  if (( ! USE_FLRIG )); then
    if remove_flrig_autostart; then
      report flrig "no longer starts when you log in, since rigctld has the radio's port again. \`radio configure --flrig\` puts flrig back in charge"
    else
      report flrig "not set up: it and rigctld can't both use the radio's port. \`radio configure --flrig\` puts flrig in charge of the radio, with rigctld passing the other programs through it"
    fi
    return
  fi
  local autostart="" others
  others="$(other_flrig_autostarts)"
  if [ -n "$others" ]; then
    autostart=" It starts when you log in, from ${others##*/}"
  elif [ -f "$FLRIG_AUTOSTART" ]; then
    autostart=" It starts when you log in"
  elif add_flrig_autostart; then
    autostart=" It now starts when you log in; start it yourself this time"
  else
    autostart=" Couldn't add it to $AUTOSTART_DIR, so start it before the other programs"
  fi
  for i in "${!FLRIG_BAUDS[@]}"; do
    [ "${FLRIG_BAUDS[i]}" = "$3" ] && index="$i"
  done
  current_name="$(fltk_get "$main" xcvr_name)"
  current_port="$(fltk_get "$rig" xcvr_serial_port)"
  SAID=() LEFT=()
  if [ "$current_name" = "$1" ] && [ "$current_port" = "$2" ] && [ "$(fltk_get "$rig" serial_baudrate)" = "$index" ] &&
    [ "$(fltk_get "$rig" ptt_via_cat)" = 1 ]; then
    report flrig "already set up.$autostart, and leave it running"
    return
  fi
  if (( ! FORCE )) && { [[ ! "$current_name" =~ ^(|NONE|$1)$ ]] || [[ ! "$current_port" =~ ^(|NONE)$ && "$current_port" != "$2" ]]; }; then
    [[ "$current_name" =~ ^(|NONE|$1)$ ]] && LEFT+=("its port ($current_port)") || LEFT+=("its radio ($current_name)")
    SAID+=("${autostart# }")
    say_changes flrig
    return
  fi
  back_up "$main"
  back_up "$rig"
  # flrig only reads a radio's settings file that has a version in it
  version="$(fltk_get "$rig" version)"
  [ -n "$version" ] || version="$(pacman -Q flrig 2> /dev/null | awk '{ sub(/-[^-]*$/, "", $2); print $2 }')"
  if ! { fltk_set "$main" flrig xcvr_name "$1" && fltk_set "$rig" "$1" version "${version:-2.0}" &&
    fltk_set "$rig" "$1" xcvr_serial_port "$2" && fltk_set "$rig" "$1" serial_baudrate "$index" &&
    fltk_set "$rig" "$1" ptt_via_cat 1; }; then
    report flrig "couldn't change its settings in $FLRIG_DIR"
    return 1
  fi
  report flrig "controls the $1 on $2 at $3 baud, PTT by CAT.$autostart, and leave it running"
}

# Pat: add rigctld to its rigs as "hampack", and use it for ARDOP and VARA
# where no rig is set
configure_pat() {
  local tmp addr modes='["ardop","varahf","varafm"]'
  if ! command -v pat > /dev/null; then
    report Pat "not installed"
    return
  fi
  if [ ! -f "$PAT_CONF" ]; then
    report Pat "skipped: it has no settings yet. Run \`pat configure\` once, then \`radio configure\` again"
    return
  fi
  if running pat; then
    report Pat "skipped, because it's running. Stop it and run \`radio configure\` again"
    return
  fi
  addr="$(jq -r '.hamlib_rigs.hampack.address // empty' "$PAT_CONF")" ||
    { report Pat "couldn't read $PAT_CONF"; return 1; }
  if [ "$addr" = "$RIGCTLD_ADDR" ] && (( ! FORCE )); then
    report Pat "already set up"
    return
  fi
  back_up "$PAT_CONF"
  tmp="$(mktemp "$PAT_CONF.XXXXXX")" || return 1
  if jq --arg addr "$RIGCTLD_ADDR" --argjson modes "$modes" --argjson force "$FORCE" '
      .hamlib_rigs = ((.hamlib_rigs // {}) + {hampack: {address: $addr, network: "tcp"}})
      | reduce $modes[] as $m (.;
          if .[$m] != null and ($force == 1 or (.[$m].rig // "") == "") then .[$m].rig = "hampack" else . end)
    ' "$PAT_CONF" > "$tmp" && chmod --reference="$PAT_CONF" "$tmp" && mv -f "$tmp" "$PAT_CONF"; then
    report Pat "rig \"hampack\" is rigctld, used by ARDOP and VARA where they had no rig"
  else
    rm -f "$tmp"
    report Pat "couldn't change $PAT_CONF"
    return 1
  fi
}

# Print a setting from fldigi's fldigi_def.xml: xml_get FILE TAG
xml_get() {
  [ -f "$1" ] || return 0
  T="$2" awk '
    index($0, "<" ENVIRON["T"] ">") == 1 {
      v = substr($0, length(ENVIRON["T"]) + 3)
      sub("</" ENVIRON["T"] ">.*$", "", v)
      print v
      exit
    }' "$1"
}

# Set one, adding it before the closing tag if it isn't there: xml_set FILE TAG VALUE
xml_set() {
  local tmp
  tmp="$(mktemp "$1.XXXXXX")" || return 1
  T="$2" V="$3" awk '
    function put() { print "<" ENVIRON["T"] ">" ENVIRON["V"] "</" ENVIRON["T"] ">"; done = 1 }
    index($0, "<" ENVIRON["T"] ">") == 1 { if (!done) put(); next }
    /^<\/FLDIGI_DEFS>/ && !done { put(); print ""; print; next }
    { print }
    END { if (!done) put() }
  ' "$1" > "$tmp" && chmod --reference="$1" "$tmp" && mv -f "$tmp" "$1"
}

# fldigi: rig control through rigctld (Hamlib's NET rigctl, model 2), with PTT
# by Hamlib, unless it has rig control set up already, and the radio's sound
# card through PortAudio. configure_fldigi CARD_NUMBER
configure_fldigi() {
  local tag set_rig=1 set_sound=0 in_device out_device audio current_in current_out i
  local tags=() values=()
  SAID=() LEFT=()
  if ! command -v fldigi > /dev/null; then
    report fldigi "not installed"
    return
  fi
  if [ ! -f "$FLDIGI_CONF" ]; then
    report fldigi "skipped: it has no settings yet. Run fldigi once, then \`radio configure\` again"
    return
  fi
  if running fldigi; then
    report fldigi "skipped, because it's running and would overwrite its settings when it quits. Quit it and run \`radio configure\` again"
    return
  fi

  if [ "$(xml_get "$FLDIGI_CONF" CHKUSEHAMLIBIS)" = 1 ] && [ "$(xml_get "$FLDIGI_CONF" HAMRIGMODEL)" = 2 ] &&
    [ "$(xml_get "$FLDIGI_CONF" HAMRIGDEVICE)" = "$RIGCTLD_ADDR" ]; then
    set_rig=0
  elif (( ! FORCE )); then
    for tag in CHKUSEHAMLIBIS CHKUSERIGCATIS CHKUSEXMLRPCIS CLIENT_TO_FLRIG; do
      if [ "$(xml_get "$FLDIGI_CONF" "$tag")" = 1 ]; then
        set_rig=0
        LEFT+=("its rig control")
        break
      fi
    done
  fi
  if (( set_rig )); then
    tags+=(CHKUSEHAMLIBIS CHKUSERIGCATIS CHKUSEXMLRPCIS CLIENT_TO_FLRIG HAMRIGMODEL HAMRIGDEVICE HAMLIBCMDPTT)
    values+=(1 0 0 0 2 "$RIGCTLD_ADDR" 1)
    SAID+=("rig control through rigctld, PTT by Hamlib")
  fi

  if [ -n "$1" ]; then
    if in_device="$(portaudio_name in "$1")" && out_device="$(portaudio_name out "$1")"; then
      # AUDIOIO is 1 for PortAudio and 3 for none; 0 (OSS) and 2 (PulseAudio) are your choice
      audio="$(xml_get "$FLDIGI_CONF" AUDIOIO)"
      current_in="$(xml_get "$FLDIGI_CONF" PORTINDEVICE)"
      current_out="$(xml_get "$FLDIGI_CONF" PORTOUTDEVICE)"
      if [ "$audio" = 1 ] && [ "$current_in" = "$in_device" ] && [ "$current_out" = "$out_device" ]; then
        :
      elif (( FORCE )) || { [[ "${audio:-3}" =~ ^(1|3|-1)$ ]] &&
        may_replace_device "$current_in" "$in_device" && may_replace_device "$current_out" "$out_device"; }; then
        set_sound=1
        tags+=(AUDIOIO PORTINDEVICE PORTININDEX PORTOUTDEVICE PORTOUTINDEX)
        values+=(1 "$in_device" -1 "$out_device" -1)
        SAID+=("sound card \"$out_device\"")
      else
        LEFT+=("its sound card")
      fi
    else
      SAID+=("choose its sound card yourself: PortAudio doesn't list the radio's")
    fi
  fi

  if [ ${#tags[@]} -gt 0 ]; then
    back_up "$FLDIGI_CONF"
    for i in "${!tags[@]}"; do
      xml_set "$FLDIGI_CONF" "${tags[i]}" "$(xml_escape "${values[i]}")" || { report fldigi "couldn't change $FLDIGI_CONF"; return 1; }
    done
  fi
  say_changes fldigi
}

# Escape a value for an XML element
xml_escape() {
  local v="${1//&/&amp;}"
  v="${v//</&lt;}"
  printf '%s\n' "${v//>/&gt;}"
}

# Print the value of the first line for a Dire Wolf setting: dw_get FILE KEYWORD
dw_get() {
  K="$2" awk '
    $1 == ENVIRON["K"] { sub(/^[ \t]*[^ \t]+[ \t]*/, ""); sub(/[ \t]+$/, ""); print; exit }
  ' "$1"
}

# Replace the first line for a setting, or add one: at the top for ADEVICE,
# which comes before any CHANNEL, or at the end for others. dw_set FILE KEYWORD VALUE
dw_set() {
  local tmp
  tmp="$(mktemp "$1.XXXXXX")" || return 1
  if [ "$2" = ADEVICE ] && ! grep -Eq '^[[:space:]]*ADEVICE([[:space:]]|$)' "$1"; then
    { echo "ADEVICE $3"; cat "$1"; } > "$tmp"
  else
    K="$2" V="$3" awk '
      function put() { print ENVIRON["K"] " " ENVIRON["V"]; done = 1 }
      $1 == ENVIRON["K"] && !done { put(); next }
      { print }
      END { if (!done) put() }
    ' "$1" > "$tmp"
  fi || { rm -f "$tmp"; return 1; }
  chmod --reference="$1" "$tmp" && mv -f "$tmp" "$1"
}

# Dire Wolf: its sound card, and PTT through rigctld, where its settings are
# still the ones HamPack ships. configure_direwolf CARD
configure_direwolf() {
  local card="$1" adevice ptt want_adevice="" want_ptt="RIG 2 $RIGCTLD_ADDR" set=() kept=()
  if [ ! -x "$HOME/.local/bin/direwolf" ]; then
    report "Dire Wolf" "not installed"
    return
  fi
  if [ ! -f "$DIREWOLF_CONF" ]; then
    report "Dire Wolf" "skipped: $DIREWOLF_CONF is missing. \`update\` puts it back"
    return
  fi
  if running direwolf; then
    report "Dire Wolf" "skipped, because it's running. Stop it and run \`radio configure\` again"
    return
  fi
  adevice="$(dw_get "$DIREWOLF_CONF" ADEVICE)"
  ptt="$(dw_get "$DIREWOLF_CONF" PTT)"
  [ -z "$card" ] || want_adevice="plug$card,DEV=0"

  if [ -n "$want_adevice" ] && [ "$adevice" != "$want_adevice" ]; then
    if (( FORCE )) || [ -z "$adevice" ] || [ "$adevice" = "$DIREWOLF_DEFAULT_ADEVICE" ]; then
      set+=(ADEVICE)
    else
      kept+=("ADEVICE $adevice")
    fi
  fi
  if [ "$ptt" != "$want_ptt" ]; then
    if (( FORCE )) || [ -z "$ptt" ] || [ "$ptt" = "$DIREWOLF_DEFAULT_PTT" ]; then
      set+=(PTT)
    else
      kept+=("PTT $ptt")
    fi
  fi

  if [ ${#set[@]} -eq 0 ] && [ ${#kept[@]} -eq 0 ]; then
    report "Dire Wolf" "already set up"
    return
  fi
  local changed=()
  if [ ${#set[@]} -gt 0 ]; then
    back_up "$DIREWOLF_CONF"
    if [[ " ${set[*]} " == *" ADEVICE "* ]]; then
      dw_set "$DIREWOLF_CONF" ADEVICE "$want_adevice" || { report "Dire Wolf" "couldn't change $DIREWOLF_CONF"; return 1; }
      changed+=("sound card $want_adevice")
    fi
    if [[ " ${set[*]} " == *" PTT "* ]]; then
      dw_set "$DIREWOLF_CONF" PTT "$want_ptt" || { report "Dire Wolf" "couldn't change $DIREWOLF_CONF"; return 1; }
      changed+=("PTT through rigctld")
    fi
  fi
  local message="" IFS=';'
  [ ${#changed[@]} -eq 0 ] || message="${changed[*]}"
  message="${message//;/, }"
  if [ ${#kept[@]} -gt 0 ]; then
    local kept_text="${kept[*]}"
    message="${message:+$message. }Left your ${kept_text//;/ and } alone: \`radio configure --force\` replaces them"
  fi
  report "Dire Wolf" "$message"
}

# Print the sound devices PortAudio lists, as fldigi and not1mm (through its
# sounddevice library) see them: "NAME<tab>HOST API<tab>INPUTS<tab>OUTPUTS",
# one to a line
portaudio_devices() {
  python3 -I -c '
import ctypes, os, sys

class DeviceInfo(ctypes.Structure):
    _fields_ = [("structVersion", ctypes.c_int), ("name", ctypes.c_char_p), ("hostApi", ctypes.c_int),
                ("maxInputChannels", ctypes.c_int), ("maxOutputChannels", ctypes.c_int)]

class HostApiInfo(ctypes.Structure):
    _fields_ = [("structVersion", ctypes.c_int), ("type", ctypes.c_int), ("name", ctypes.c_char_p)]

try:
    pa = ctypes.CDLL("libportaudio.so.2")
except OSError:
    sys.exit(1)
pa.Pa_GetDeviceInfo.restype = ctypes.POINTER(DeviceInfo)
pa.Pa_GetHostApiInfo.restype = ctypes.POINTER(HostApiInfo)
# PortAudio and ALSA complain on stderr while they look for devices
saved, null = os.dup(2), os.open(os.devnull, os.O_WRONLY)
os.dup2(null, 2)
try:
    if pa.Pa_Initialize() != 0:
        sys.exit(1)
    for i in range(pa.Pa_GetDeviceCount()):
        d = pa.Pa_GetDeviceInfo(i).contents
        api = pa.Pa_GetHostApiInfo(d.hostApi).contents.name.decode(errors="replace")
        print("%s\t%s\t%d\t%d" % (d.name.decode(errors="replace"), api, d.maxInputChannels, d.maxOutputChannels))
    sys.stdout.flush()
    pa.Pa_Terminate()
finally:
    os.dup2(saved, 2)
'
}

# Print PortAudio's name for the radio's sound card, for input or output:
# PipeWire's description of it, through PortAudio's JACK support, which stays
# the same from boot to boot, if just one device has it. Failing that, ALSA's
# name for it, which has the card's number in it: "USB Audio CODEC: USB Audio
# (hw:1,0)". portaudio_name in|out CARD_NUMBER, with PORTAUDIO_DEVICES set
portaudio_name() {
  local column=3 desc="$PW_IN_DESC" names
  [ "$1" = in ] || { column=4; desc="$PW_OUT_DESC"; }
  names="$(awk -F'\t' -v c="$column" '$c > 0 { print $1 }' <<< "$PORTAUDIO_DEVICES")"
  if [ -n "$desc" ] && [ "$(grep -cxF "$desc" <<< "$names")" -eq 1 ]; then
    echo "$desc"
  elif [ -n "$2" ]; then
    grep -F "(hw:$2," <<< "$names" | head -1 | grep .
  else
    return 1
  fi
}

# Whether a device setting names the card radio would set, or the same card
# under the number it had before: may_replace_device CURRENT NEW
may_replace_device() {
  is_default_device "$1" || (( FORCE )) ||
    { [[ "$2" == *"(hw:"* ]] && [[ "$1" == "${2%(hw:*}(hw:"*")" ]]; }
}

# not1mm: rig control through rigctld, unless it uses flrig, TCI or another
# rigctld already, and the radio's sound card for its voice keyer.
# configure_not1mm CARD_NUMBER
configure_not1mm() {
  local tmp rig_state device current set_rig=0 set_sound=0
  SAID=() LEFT=()
  if [ ! -x "$HOME/.local/bin/not1mm" ]; then
    report not1mm "not installed"
    return
  fi
  if [ ! -f "$NOT1MM_CONF" ]; then
    report not1mm "skipped: it has no settings yet. Run not1mm once, then \`radio configure\` again"
    return
  fi
  if running not1mm; then
    report not1mm "skipped, because it's running and would overwrite its settings when it quits. Quit it and run \`radio configure\` again"
    return
  fi
  rig_state="$(jq -r --arg addr "$RIGCTLD_ADDR" '
      if .userigctld == true and "\(.CAT_ip):\(.CAT_port)" == $addr then "already"
      elif .userigctld == true or .useflrig == true or .usetci == true then "theirs"
      else "empty" end' "$NOT1MM_CONF")" ||
    { report not1mm "couldn't read $NOT1MM_CONF"; return 1; }
  case "$rig_state" in
    already) ;;
    theirs)
      if (( FORCE )); then
        set_rig=1
      else
        LEFT+=("its rig control")
      fi ;;
    *) set_rig=1 ;;
  esac
  (( ! set_rig )) || SAID+=("rig control through rigctld")

  if [ -n "$1" ]; then
    if device="$(portaudio_name out "$1")"; then
      current="$(jq -r '.sounddevice // ""' "$NOT1MM_CONF")"
      if [ "$current" = "$device" ]; then
        :
      elif may_replace_device "$current" "$device"; then
        set_sound=1
        SAID+=("voice keyer on \"$device\"")
      else
        LEFT+=("its sound card ($current)")
      fi
    else
      SAID+=("choose its sound card yourself: PortAudio doesn't list the radio's")
    fi
  fi

  if (( set_rig || set_sound )); then
    back_up "$NOT1MM_CONF"
    tmp="$(mktemp "$NOT1MM_CONF.XXXXXX")" || return 1
    if ! jq --arg ip "${RIGCTLD_ADDR%:*}" --argjson port "${RIGCTLD_ADDR#*:}" --arg device "${device:-}" \
      --argjson rig "$set_rig" --argjson sound "$set_sound" '
        (if $rig == 1 then .userigctld = true | .useflrig = false | .usetci = false | .CAT_ip = $ip | .CAT_port = $port else . end)
        | (if $sound == 1 then .sounddevice = $device else . end)
      ' "$NOT1MM_CONF" > "$tmp" || ! chmod --reference="$NOT1MM_CONF" "$tmp" || ! mv -f "$tmp" "$NOT1MM_CONF"; then
      rm -f "$tmp"
      report not1mm "couldn't change $NOT1MM_CONF"
      return 1
    fi
  fi
  say_changes not1mm
}

# QLog keeps its rig profiles in its log database. Add a "HamPack" profile for
# rigctld (Hamlib's NET rigctl) and select it, if there are no profiles yet.
# The values are those QLog 0.54's settings dialog gives a new profile. QLog
# keeps recent changes in qlog.db-wal, so the log is backed up (to BACKUP)
# through SQLite, which includes them. qlog_profile BACKUP prints done, kept,
# added, old (a database without the columns these need) or the error
qlog_profile() {
  python3 -I -c '
import sqlite3, sys
db, backup, host, port, force = sys.argv[1], sys.argv[2], sys.argv[3], int(sys.argv[4]), sys.argv[5] == "1"
profile = {
    "profile_name": "HamPack", "model": 2, "port_pathname": "", "hostname": host, "netport": port,
    "baudrate": 0, "databits": 0, "stopbits": 0.0, "flowcontrol": "", "parity": "",
    "pollinterval": 500, "txfreq_start": 0.0, "txfreq_end": 0.0, "get_freq": 1, "get_mode": 1,
    "get_vfo": 1, "get_pwr": 1, "rit_offset": 0.0, "xit_offset": 0.0, "get_rit": 0, "get_xit": 0,
    "default_pwr": 100.0, "get_ptt": 0, "qsy_wiping": 1, "get_key_speed": 1, "assigned_cw_key": " ",
    "key_speed_sync": 0, "driver": 1, "dxspot2rig": 0, "ptt_type": "", "ptt_port_pathname": "",
    "rts": "", "dtr": "", "civaddr": None, "share_rigctld": 0, "rigctld_port": 4532,
    "rigctld_path": "", "rigctld_args": "", "get_split": 0, "cwkey_output": 0, "selected": 1,
}
try:
    con = sqlite3.connect(db)
    columns = {row[1].lower() for row in con.execute("PRAGMA table_info(rig_profiles)")}
    if not set(profile) <= columns:
        print("old")
        sys.exit(0)
    if con.execute("SELECT 1 FROM rig_profiles WHERE driver = 1 AND model = 2 AND hostname = ? AND netport = ? AND IFNULL(selected, 0) = 1",
                   (host, port)).fetchone():
        print("done")
        sys.exit(0)
    if con.execute("SELECT 1 FROM rig_profiles WHERE profile_name != ?", ("HamPack",)).fetchone() and not force:
        print("kept")
        sys.exit(0)
    copy = sqlite3.connect(backup)
    con.backup(copy)
    copy.close()
    with con:
        con.execute("DELETE FROM rig_profiles WHERE profile_name = ?", ("HamPack",))
        con.execute("UPDATE rig_profiles SET selected = 0")
        con.execute("INSERT INTO rig_profiles (%s) VALUES (%s)" % (", ".join(profile), ", ".join("?" * len(profile))),
                    list(profile.values()))
    print("added")
except (sqlite3.Error, OSError) as e:
    print(e)
' "$QLOG_DB" "$1" "${RIGCTLD_ADDR%:*}" "${RIGCTLD_ADDR#*:}" "$FORCE"
}

configure_qlog() {
  local result
  if ! flatpak info "$QLOG_FLATPAK" > /dev/null 2>&1; then
    report QLog "not installed"
    return
  fi
  if [ ! -f "$QLOG_DB" ]; then
    report QLog "skipped: it has no log yet. Run QLog once, then \`radio configure\` again"
    return
  fi
  if running qlog; then
    report QLog "skipped, because it's running and would overwrite its rig profiles. Quit it and run \`radio configure\` again"
    return
  fi
  local backup
  backup="$QLOG_DB.bak-$(date +%Y%m%d-%H%M%S)"
  result="$(qlog_profile "$backup")"
  case "$result" in
    added)
      BACKUPS+=("$backup")
      report QLog "rig profile \"HamPack\" is rigctld, and selected" ;;
    done) report QLog "already set up" ;;
    kept) report QLog "left alone: it has rig profiles already. \`radio configure --force\` adds one for rigctld and selects it" ;;
    old) report QLog "skipped: its log is older than this radio knows. Open QLog once to update it, then \`radio configure\` again" ;;
    *)
      report QLog "couldn't change $QLOG_DB: $result"
      return 1 ;;
  esac
}

# POTACAT: add rigctld to My Rigs as a "rigctld Network" rig, and make it the
# active one, unless rigs are set up already. Rigs and the active rig are kept
# in settings.json; the connection (catTarget) is too, until there's an
# operator profile, which then keeps it in profiles/CALL/settings.json.
# configure_potacat NAME
configure_potacat() {
  local global="$POTACAT_DIR/settings.json" profile cat_file state tmp target
  target="$(jq -nc --arg host "${RIGCTLD_ADDR%:*}" --argjson port "${RIGCTLD_ADDR#*:}" '{type: "rigctldnet", host: $host, port: $port}')"
  if [ ! -x "$HOME/.local/bin/POTACAT.AppImage" ]; then
    report POTACAT "not installed"
    return
  fi
  if [ ! -f "$global" ]; then
    report POTACAT "skipped: it has no settings yet. Run POTACAT once, then \`radio configure\` again"
    return
  fi
  if running potacat; then
    report POTACAT "skipped, because it's running and would overwrite its settings when it quits. Quit it and run \`radio configure\` again"
    return
  fi
  profile="$(jq -r 'if .activeProfile and (has("catTarget") | not) then .activeProfile else "" end' "$global")" ||
    { report POTACAT "couldn't read $global"; return 1; }
  cat_file="$global"
  [ -z "$profile" ] || cat_file="$POTACAT_DIR/profiles/$profile/settings.json"

  local current active rigs
  current="$(jq -c '.catTarget // null' "$cat_file" 2> /dev/null || echo null)"
  if ! { active="$(jq -r '.activeRigId // ""' "$global")" && rigs="$(jq '.rigs // [] | length' "$global")"; }; then
    report POTACAT "couldn't read $global"
    return 1
  fi
  if [ "$active" = rig_hampack ] && jq -en --argjson a "$current" --argjson b "$target" '$a == $b' > /dev/null; then
    state="already"
  elif (( rigs > 0 )) || [ "$current" != null ]; then
    state="theirs"
  else
    state="empty"
  fi
  local set_rig=0 set_sound=0 sound=""
  SAID=() LEFT=()
  case "$state" in
    already) ;;
    theirs)
      if (( FORCE )); then
        set_rig=1
      else
        LEFT+=("its own radio")
      fi ;;
    *) set_rig=1 ;;
  esac
  (( ! set_rig )) || SAID+=("rig \"$1 (HamPack's rigctld)\" is rigctld, and active")

  # The sound card goes on HamPack's rig only. POTACAT keeps Chromium's device
  # ids, which only it can see, with the device's name (its label) beside
  # each. When a saved id matches no device, POTACAT takes the one device
  # whose name is the saved label (lib/audio-device-heal.js, at launch). So
  # the rig gets PipeWire's names for the card as labels, which is how
  # Chromium names PipeWire's devices, and ids that match nothing.
  if [ -n "$PW_IN_NAME" ] && { (( set_rig )) || jq -e 'any(.rigs // [] | .[]; .id == "rig_hampack")' "$global" > /dev/null; }; then
    sound="$(jq -r --arg in "$PW_IN_DESC" --arg out "$PW_OUT_DESC" '
        (first(.rigs // [] | .[] | select(.id == "rig_hampack")) // {}) as $r
        | def unset(id): (id // "") as $i | $i == "" or $i == "default" or $i == "communications" or ($i | startswith("hampack:"));
          if $r.remoteAudioInputLabel == $in and $r.remoteAudioOutputLabel == $out then "already"
          elif unset($r.remoteAudioInput) and unset($r.remoteAudioOutput) then "empty"
          else "theirs" end' "$global")" || { report POTACAT "couldn't read $global"; return 1; }
    if [ "$sound" = empty ] || { [ "$sound" = theirs ] && (( FORCE )); }; then
      set_sound=1
      SAID+=("sound card \"$PW_OUT_DESC\", which POTACAT finds by name when it starts")
    elif [ "$sound" = theirs ]; then
      LEFT+=("its sound card")
    fi
  fi

  if (( set_rig || set_sound )); then
    back_up "$global"
    tmp="$(mktemp "$global.XXXXXX")" || return 1
    if ! jq --argjson t "$target" --arg name "$1 (HamPack's rigctld)" --arg cat "$cat_file" --arg global "$global" \
      --argjson rig "$set_rig" --argjson sound "$set_sound" \
      --arg in_id "hampack:$PW_IN_NAME" --arg in_label "$PW_IN_DESC" --arg out_id "hampack:$PW_OUT_NAME" --arg out_label "$PW_OUT_DESC" '
        (first(.rigs // [] | .[] | select(.id == "rig_hampack")) // {}) as $old
        | ($old
           + (if $rig == 1 then {id: "rig_hampack", name: $name, catTarget: $t} else {} end)
           + (if $sound == 1 then {remoteAudioInput: $in_id, remoteAudioInputLabel: $in_label,
                                   remoteAudioOutput: $out_id, remoteAudioOutputLabel: $out_label} else {} end)) as $new
        | .rigs = ([(.rigs // [])[] | select(.id != "rig_hampack")] + [$new])
        | if $rig == 1 then .activeRigId = "rig_hampack" | (if $cat == $global then .catTarget = $t else . end) else . end
      ' "$global" > "$tmp" || ! chmod --reference="$global" "$tmp" || ! mv -f "$tmp" "$global"; then
      rm -f "$tmp"
      report POTACAT "couldn't change $global"
      return 1
    fi
  fi
  if (( set_rig )) && [ "$cat_file" != "$global" ]; then
    back_up "$cat_file"
    mkdir -p "$(dirname "$cat_file")" && { [ -f "$cat_file" ] || echo '{}' > "$cat_file"; } || return 1
    tmp="$(mktemp "$cat_file.XXXXXX")" || return 1
    if ! jq --argjson t "$target" '.catTarget = $t' "$cat_file" > "$tmp" || ! chmod --reference="$cat_file" "$tmp" || ! mv -f "$tmp" "$cat_file"; then
      rm -f "$tmp"
      report POTACAT "couldn't change $cat_file"
      return 1
    fi
  fi
  say_changes POTACAT
}

# Graywolf keeps its settings in graywolf.db. If it has no channels yet and
# the radio has a sound card, add input and output devices for the card and a
# channel using them, with Graywolf's defaults (1200 baud AFSK, APRS). Then
# set PTT to rigctld on each channel that can transmit and has none (or, with
# --force, any other). graywolf_setup check|BACKUP DEVICE CHANNEL_NAME prints
# "ADDED CHANGED KEPT": whether a channel is (or was) added, the number of
# channels whose PTT is (or was) changed, and the number left alone. Or it
# prints "none" with no channel that transmits, or the error. With BACKUP it
# makes the changes, backing up the database through SQLite first, which
# includes what's still in graywolf.db-wal.
graywolf_setup() {
  python3 -I -c '
import datetime, sqlite3, sys
db, backup, addr, force, device, channel_name = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4] == "1", sys.argv[5], sys.argv[6]
try:
    con = sqlite3.connect(db)
    add_channel = bool(device) and not con.execute("SELECT 1 FROM channels").fetchone()
    channels = [row[0] for row in con.execute("SELECT id FROM channels WHERE output_device_id != 0 ORDER BY id")]
    if not channels and not add_channel:
        print("none")
        sys.exit(0)
    ptt = {row[0]: (row[1], row[2]) for row in con.execute("SELECT channel_id, method, device FROM ptt_configs")}
    change, kept = [], 0
    for channel in channels:
        method, ptt_device = ptt.get(channel, ("none", ""))
        if (method, ptt_device) == ("rigctld", addr):
            continue
        if method in ("none", "") or force:
            change.append(channel)
        else:
            kept += 1
    if backup != "check" and (change or add_channel):
        copy = sqlite3.connect(backup)
        con.backup(copy)
        copy.close()
        now = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%d %H:%M:%S.%f+00:00")
        with con:
            if add_channel:
                ids = {}
                for direction in ("input", "output"):
                    row = con.execute("SELECT id FROM audio_devices WHERE direction = ? AND source_type = ? AND source_path = ?",
                                      (direction, "soundcard", device)).fetchone()
                    if row is None:
                        row = (con.execute("INSERT INTO audio_devices (name, direction, source_type, source_path, sample_rate, "
                                           "channels, format, gain_db, created_at, updated_at) VALUES (?, ?, ?, ?, 48000, 1, ?, 0, ?, ?)",
                                           (channel_name + " " + direction, direction, "soundcard", device, "s16le", now, now)).lastrowid,)
                    ids[direction] = row[0]
                channel = con.execute("INSERT INTO channels (name, input_device_id, output_device_id, created_at, updated_at) "
                                      "VALUES (?, ?, ?, ?, ?)", (channel_name, ids["input"], ids["output"], now, now)).lastrowid
                change.append(channel)
            for channel in change:
                if channel in ptt:
                    con.execute("UPDATE ptt_configs SET method = ?, device = ?, updated_at = ? WHERE channel_id = ?",
                                ("rigctld", addr, now, channel))
                else:
                    con.execute("INSERT INTO ptt_configs (channel_id, method, device, gpio_pin, ptt_method, gpio_line, "
                                "invert, slot_time_ms, persist, dwait_ms, created_at, updated_at) "
                                "VALUES (?, ?, ?, 0, 0, 0, 0, 10, 63, 0, ?, ?)", (channel, "rigctld", addr, now, now))
            change = [c for c in change if c in channels]
    print(int(add_channel), len(change), kept)
except (sqlite3.Error, OSError) as e:
    print(e)
' "$GRAYWOLF_DB" "$1" "$RIGCTLD_ADDR" "$FORCE" "$2" "$3"
}

# configure_graywolf CARD NAME, where CARD is ALSA's name for the radio's
# sound card (hw:CARD=CODEC), or nothing
configure_graywolf() {
  local result added changed kept backup was_active=0 web="http://localhost:8080" device=""
  local manual="in its web UI ($web), set each channel's PTT to rigctld, $RIGCTLD_ADDR"
  [ -z "$1" ] || device="plug$1,DEV=0"
  if [ ! -x "$HOME/.local/bin/graywolf" ]; then
    report Graywolf "not installed"
    return
  fi
  if [ ! -f "$GRAYWOLF_DB" ]; then
    report Graywolf "skipped: it has no settings yet. Open its web UI ($web) once, then \`radio configure\` again"
    return
  fi
  result="$(graywolf_setup check "$device" "$2")"
  read -r added changed kept <<< "$result"
  if [ "$added" = 1 ] || [[ "$changed" =~ ^[1-9][0-9]*$ ]]; then
    # It runs as a system service, and reads its settings when it starts
    if systemctl is-active --quiet graywolf 2> /dev/null; then
      if ! sudo systemctl stop graywolf; then
        report Graywolf "skipped: couldn't stop it to change its settings. Instead, $manual"
        return
      fi
      was_active=1
    fi
    backup="$GRAYWOLF_DB.bak-$(date +%Y%m%d-%H%M%S)"
    result="$(graywolf_setup "$backup" "$device" "$2")"
    (( ! was_active )) || sudo systemctl start graywolf
    read -r added changed kept <<< "$result"
  fi
  if [ "$added" = none ]; then
    report Graywolf "skipped: it has no channel that transmits yet. Add one in its web UI ($web) with PTT rigctld, $RIGCTLD_ADDR"
    return
  elif ! [[ "$added" =~ ^[01]$ ]]; then
    report Graywolf "couldn't change $GRAYWOLF_DB: $result"
    return 1
  fi
  (( added == 0 && changed == 0 )) || BACKUPS+=("$backup")
  SAID=() LEFT=()
  (( added == 0 )) || SAID+=("a channel on the radio's sound card ($device), 1200 baud APRS, PTT through rigctld")
  (( changed == 0 )) || SAID+=("PTT through rigctld on $changed$( (( added )) && echo " other") channel$( ((changed == 1)) || echo s)")
  (( kept == 0 )) || LEFT+=("$kept channel$( ((kept == 1)) || echo s) with PTT of its own")
  say_changes Graywolf
}

# Write rigctld's user service, and start it if it can run now:
# write_rigctld DESCRIPTION PORT RIGCTLD_ARGS..., with PORT the radio's
# serial port, or nothing when rigctld doesn't open it itself (with flrig).
# With a port, rigctld is bound to it: systemd starts it when the port
# appears (the radio plugged in or switched on, or at login if it's there
# already) and stops it when the port goes. Without one, it starts at login.
# Prints "started", or "waiting" for a radio that isn't there yet
write_rigctld() {
  local unit description="$1" port="$2" device="" wanted=default.target
  shift 2
  if [ -n "$port" ]; then
    device="$(systemd-escape --path --suffix=device "$port")" || return 1
    wanted="$device"
  fi
  unit="[Unit]
Description=Hamlib rigctld for $description (written by HamPack's radio configure)${device:+
BindsTo=$device
After=$device}

[Service]
ExecStart=/usr/bin/rigctld $* -T ${RIGCTLD_ADDR%:*} -t ${RIGCTLD_ADDR#*:}
Restart=on-failure
RestartSec=5

[Install]
WantedBy=$wanted"
  mkdir -p "$(dirname "$RIGCTLD_UNIT")" || return 1
  printf '%s\n' "$unit" > "$RIGCTLD_UNIT" || return 1
  # reenable clears what an earlier version of the unit was wanted by
  systemctl --user daemon-reload && systemctl --user reenable hampack-rigctld 2> /dev/null || return 1
  if [ -n "$port" ] && [ ! -e "$DEVDIR/${port#/dev/}" ]; then
    echo waiting
  else
    systemctl --user restart hampack-rigctld && echo started
  fi
}

# Print a field of a radio in radios.conf: conf_field NAME FIELD
conf_field() {
  awk -v name="$1" -v field="$2" '
    /^\[/ { in_radio = ($0 == "[" name "]"); next }
    in_radio && index($0, field "=") == 1 { print substr($0, length(field) + 2); exit }
  ' "$RADIOS_CONF"
}

# Print the name radios.conf gives a Hamlib model, or nothing
hamlib_name() {
  awk -F= -v m="$1" '/^\[/ { name = substr($0, 2, length($0) - 2) } $1 == "hamlib" && $2 == m { print name; exit }' "$RADIOS_CONF"
}

# radio configure: set up rigctld for a radio and point the programs at it
configure() {
  local number="" model="" radio="" sound_card="" sound_dev="" was_running=0 name port="" baud="" card card_sys
  local flrig_name="" flrig_port=12345 no_cat=0 ptt="" ptt_type="" ptt_device="" ptt_text="" sound_only total
  FORCE=0 BACKUPS=() USE_FLRIG=0
  while [ $# -gt 0 ]; do
    case "$1" in
      --force) FORCE=1 ;;
      --flrig) USE_FLRIG=1 ;;
      --no-cat) no_cat=1 ;;
      --ptt)
        [[ "${2:-}" =~ ^(cm108|rts|dtr|vox)$ ]] || { usage >&2; return 2; }
        ptt="$2"
        shift ;;
      --model)
        [[ "${2:-}" =~ ^[0-9]+$ ]] || { usage >&2; return 2; }
        model="$2"
        shift ;;
      [1-9]*)
        [[ "$1" =~ ^[0-9]+$ ]] || { usage >&2; return 2; }
        number="$1" ;;
      *) usage >&2; return 2 ;;
    esac
    shift
  done

  # Radios with a serial port, then sound cards with none, numbered as `radio` lists them
  find_radios
  sound_only="$(sound_only_cards)"
  local sound_cards=()
  [ -z "$sound_only" ] || mapfile -t sound_cards <<< "$sound_only"
  total=$(( ${#RADIOS[@]} + ${#sound_cards[@]} ))
  if (( total == 0 )); then
    echo "No USB serial ports or sound cards found: is the radio plugged in and switched on?"
    return 1
  fi
  if [ -z "$number" ]; then
    if (( total > 1 )); then
      echo "There are $total radios or interfaces plugged in. Give the number \`radio\` lists for the one to set up, as in \`radio configure 2\`"
      return 2
    fi
    number=1
  fi
  if (( number > total )); then
    echo "There's no radio $number: \`radio\` lists $total"
    return 2
  fi
  if (( number <= ${#RADIOS[@]} )); then
    radio="${RADIOS[number - 1]}"
  else
    read -r sound_card sound_dev <<< "${sound_cards[number - ${#RADIOS[@]} - 1]}"
    no_cat=1
  fi

  if (( no_cat && USE_FLRIG )); then
    echo "flrig needs a radio with CAT to control, so --flrig can't set up a radio with none."
    return 2
  fi
  if (( no_cat )) && [ -n "$model" ]; then
    echo "With no CAT, rigctld doesn't talk to the radio, so --model doesn't apply."
    return 2
  fi
  if [ -n "$ptt" ] && (( ! no_cat )); then
    echo "--ptt is for a radio with no CAT: with CAT, the radio is keyed through it. Add --no-cat if this radio has none."
    return 2
  fi
  if [ -n "$sound_card" ] && [[ "$ptt" =~ ^(rts|dtr)$ ]]; then
    echo "This sound card has no serial port for --ptt $ptt: use cm108 or vox."
    return 2
  fi
  if [ -n "$radio" ] && (( no_cat )) && [ -z "$ptt" ]; then
    echo "Give the way the interface keys the radio: --ptt rts or --ptt dtr (its serial port's lines; a Digirig Mobile uses rts), --ptt cm108 (its sound card's PTT pin) or --ptt vox."
    return 2
  fi
  if (( USE_FLRIG )); then
    if ! command -v flrig > /dev/null; then
      echo "flrig isn't installed."
      return 1
    fi
    if running flrig; then
      echo "Quit flrig first: it has the radio's port open, and saves its settings when it quits."
      return 1
    fi
  fi

  # rigctld has the port open, if radio configure has run before
  if systemctl --user is-active --quiet hampack-rigctld 2> /dev/null; then
    systemctl --user stop hampack-rigctld
    was_running=1
  fi

  if (( no_cat )); then
    # rigctld's Dummy radio (Hamlib model 1) only keys the radio, its own way
    model=1
    if [ -n "$radio" ]; then
      read -ra ID_PORTS <<< "${RADIO_PORTS[$radio]}"
      port="$(port_path "${ID_PORTS[0]}")"
      card_sys="$(card_of "$radio")"
      name="radio on the $(attr "${PORT_USB[${ID_PORTS[0]}]}" product)"
    else
      card_sys="$sound_card"
      name="radio on the $(attr "$sound_dev" manufacturer) $(attr "$sound_dev" product)"
      name="${name//  / }"
      if [ -z "$ptt" ]; then
        cm108_compatible "$sound_dev" && ptt=cm108 || ptt=vox
      fi
    fi
    case "$ptt" in
      cm108)
        local cm108_dev="${CARD_USB[$card_sys]:-}"
        if [ -z "$cm108_dev" ] || ! cm108_compatible "$cm108_dev" || ! ptt_device="$(hidraw_path "$cm108_dev")"; then
          echo "The radio's sound card has no CM108 PTT pin radio can find: give another --ptt."
          (( ! was_running )) || systemctl --user start hampack-rigctld
          return 1
        fi
        ptt_type=CM108
        ptt_text="PTT through its sound card's CM108 pin, $ptt_device" ;;
      rts | dtr)
        ptt_device="$port"
        ptt_type="${ptt^^}"
        ptt_text="PTT by ${ptt^^} on $port" ;;
      vox)
        ptt_text="PTT by VOX: the radio keys itself on the audio" ;;
    esac
  else
    identify "$radio" always
    if [ -z "$ID_CAT_PORT" ]; then
      echo "Couldn't set it up: nothing answered on ${ID_PORTS[*]}."
      [ ${#ID_NOTES[@]} -eq 0 ] || printf '  %s\n' "${ID_NOTES[@]}"
      (( ! ID_ASKED )) || echo "Check it's switched on and its CAT rate is one of ${BAUDS[*]} baud. If the radio has no CAT, \`radio configure --no-cat --ptt HOW\` sets it up to be keyed."
      (( ! was_running )) || systemctl --user start hampack-rigctld
      return 1
    fi

    if [ -n "$model" ]; then
      name="$(hamlib_name "$model")"
      name="${name:-radio}"
    elif [ -n "$ID_MODELS" ] && [ "$(wc -l <<< "$ID_MODELS")" -eq 1 ]; then
      name="${ID_MODELS%|*}"
      model="${ID_MODELS#*|}"
    else
      if [ -n "$ID_MODELS" ]; then
        echo "Couldn't tell which radio it is: it's $(models_text "$ID_MODELS")."
      else
        echo "Couldn't tell which radio it is: it's ${ID_ANSWER}."
      fi
      echo "Give its Hamlib model number (\`rigctl -l\` lists them), as in \`radio configure --model 2045\`"
      (( ! was_running )) || systemctl --user start hampack-rigctld
      return 1
    fi
    if (( USE_FLRIG )); then
      flrig_name="$(conf_field "$name" flrig)"
      if [ -z "$flrig_name" ]; then
        echo "radio doesn't know flrig's name for the $name, if flrig has a driver for it. Choose the radio in flrig yourself, or run \`radio configure\` without --flrig."
        (( ! was_running )) || systemctl --user start hampack-rigctld
        return 1
      fi
      flrig_port="$(fltk_get "$FLRIG_DIR/$flrig_name.prefs" xmlport)"
      flrig_port="${flrig_port:-12345}"
    fi
    port="$(port_path "$ID_CAT_PORT")"
    baud="$ID_BAUD"
    card_sys="$(card_of "$radio")"
  fi
  card=""
  [ -z "$card_sys" ] || card="hw:CARD=$(attr "$SYSFS/class/sound/$card_sys" id)"
  local card_number="${card_sys#card}" pipewire=0
  find_pipewire_nodes "$card_number" && pipewire=1
  PORTAUDIO_DEVICES="$(portaudio_devices)" || PORTAUDIO_DEVICES=""

  if (( no_cat )); then
    echo "Setting up the $name, with no CAT: $ptt_text"
  else
    echo "Setting up the $name (Hamlib model $model), on $port at $baud baud$( (( USE_FLRIG )) && echo ", through flrig")"
  fi
  echo
  local rigctld=""
  if (( USE_FLRIG )); then
    rigctld="$(write_rigctld "flrig, which controls the $name" "" -m 4 -r "127.0.0.1:$flrig_port")"
  elif (( no_cat )); then
    rigctld="$(write_rigctld "the $name, which only keys it" "$port" -m 1 ${ptt_type:+-p "$ptt_device" -P "$ptt_type"})"
  else
    rigctld="$(write_rigctld "the $name" "$port" -m "$model" -r "$port" -s "$baud")"
  fi
  if [ "$rigctld" = started ] && (( USE_FLRIG )); then
    report rigctld "runs as the hampack-rigctld user service, on $RIGCTLD_ADDR, and passes everything to flrig"
  elif [ "$rigctld" = started ] && (( no_cat )) && [ -z "$port" ]; then
    report rigctld "runs as the hampack-rigctld user service, on $RIGCTLD_ADDR, and keys the radio when the programs transmit"
  elif [ "$rigctld" = started ] && (( no_cat )); then
    report rigctld "runs as the hampack-rigctld user service, on $RIGCTLD_ADDR, whenever the interface is plugged in, and keys the radio when the programs transmit"
  elif [ "$rigctld" = started ]; then
    report rigctld "runs as the hampack-rigctld user service, on $RIGCTLD_ADDR, whenever the radio is plugged in and on"
  elif [ "$rigctld" = waiting ]; then
    report rigctld "runs as the hampack-rigctld user service, on $RIGCTLD_ADDR, from when the radio is plugged in and on"
  else
    report rigctld "couldn't start: see \`systemctl --user status hampack-rigctld\`"
  fi
  [ -z "$port" ] || [[ "$port" == /dev/serial/by-id/* ]] ||
    report "" "$port has no stable name, so it may be a different port after a reboot. Run \`radio configure\` again if so"

  if flatpak info "$WSJTX_FLATPAK" > /dev/null 2>&1; then
    configure_qt_app WSJT-X "$WSJTX_CONF" wsjtx wsjtx
  else
    report WSJT-X "not installed"
  fi
  if [ -x "$HOME/.local/bin/JS8Call" ]; then
    configure_qt_app JS8Call "$JS8CALL_CONF" JS8Call js8call
  else
    report JS8Call "not installed"
  fi
  configure_flrig "$flrig_name" "$port" "$baud"
  configure_pat
  configure_fldigi "$card_number"
  configure_direwolf "$card"
  configure_not1mm "$card_number"
  configure_qlog
  configure_potacat "$name"
  configure_graywolf "$card" "$name"

  mkdir -p "$HAMPACK_STATE" &&
    printf 'name=%s\nhamlib=%s\nport=%s\nbaud=%s\ncard=%s\ncontroller=%s\nptt=%s\n' "$name" "$model" "$port" "$baud" "$card" \
      "$( (( USE_FLRIG )) && echo flrig || echo rigctld)" "${ptt:-cat}" > "$HAMPACK_STATE/radio"

  echo
  if [ -z "$card" ]; then
    echo "No sound card was found with the radio: choose the one it's connected to in each program yourself."
  elif (( pipewire )); then
    echo "The radio's sound card is \"$PW_OUT_DESC\" ($card)."
  else
    echo "PipeWire didn't list the radio's sound card, $card (\"$(attr "${CARD_USB[$card_sys]}" product)\"), so choose it yourself in WSJT-X, JS8Call and POTACAT."
  fi
  [ ${#BACKUPS[@]} -eq 0 ] || { echo "The settings were backed up first, to:"; printf '  %s\n' "${BACKUPS[@]}"; }
}

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