#!/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] [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"
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 and Dire Wolf 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
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, 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:
        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" ]
}

# 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="$(matching "$ANSWER_FIELD" "$ANSWER_VALUE")"
  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="$(matching "$ANSWER_FIELD" "$ANSWER_VALUE")"
        [ -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

  if ! find_radios; 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)"
    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
}

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

# WSJT-X and JS8Call share their settings: point one at rigctld, with PTT by
# CAT. configure_qt_app NAME FILE PROCESS
configure_qt_app() {
  local name="$1" file="$2" rig net
  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
    report "$name" "already set up"
    return
  fi
  if [ -n "$rig" ] && [ "$rig" != None ] && (( ! FORCE )); then
    report "$name" "left alone: it's set up for $rig. \`radio configure --force\` replaces that"
    return
  fi
  back_up "$file"
  if ! { ini_set "$file" Configuration Rig "Hamlib NET rigctl" &&
    ini_set "$file" Configuration CATNetworkPort "$RIGCTLD_ADDR" &&
    ini_set "$file" Configuration PTTMethod "$PTT_CAT"; }; then
    report "$name" "couldn't change $file"
    return 1
  fi
  report "$name" "rig control through rigctld, PTT by CAT"
}

# 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
configure_fldigi() {
  local tag
  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
    report fldigi "already set up"
    return
  fi
  if (( ! FORCE )); then
    for tag in CHKUSEHAMLIBIS CHKUSERIGCATIS CHKUSEXMLRPCIS CLIENT_TO_FLRIG; do
      if [ "$(xml_get "$FLDIGI_CONF" "$tag")" = 1 ]; then
        report fldigi "left alone: it has rig control set up already. \`radio configure --force\` replaces that"
        return
      fi
    done
  fi
  back_up "$FLDIGI_CONF"
  if ! { xml_set "$FLDIGI_CONF" CHKUSEHAMLIBIS 1 && xml_set "$FLDIGI_CONF" CHKUSERIGCATIS 0 &&
    xml_set "$FLDIGI_CONF" CHKUSEXMLRPCIS 0 && xml_set "$FLDIGI_CONF" CLIENT_TO_FLRIG 0 &&
    xml_set "$FLDIGI_CONF" HAMRIGMODEL 2 && xml_set "$FLDIGI_CONF" HAMRIGDEVICE "$RIGCTLD_ADDR" &&
    xml_set "$FLDIGI_CONF" HAMLIBCMDPTT 1; }; then
    report fldigi "couldn't change $FLDIGI_CONF"
    return 1
  fi
  report fldigi "rig control through rigctld, PTT by Hamlib"
}

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

# Write and (re)start rigctld's user service: write_rigctld NAME HAMLIB PORT BAUD
write_rigctld() {
  local unit
  unit="[Unit]
Description=Hamlib rigctld for the $1 (written by HamPack's radio configure)

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

[Install]
WantedBy=default.target"
  mkdir -p "$(dirname "$RIGCTLD_UNIT")" || return 1
  printf '%s\n' "$unit" > "$RIGCTLD_UNIT" || return 1
  systemctl --user daemon-reload &&
    systemctl --user enable hampack-rigctld 2> /dev/null &&
    systemctl --user restart hampack-rigctld
}

# 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 was_running=0 name port baud card
  FORCE=0 BACKUPS=()
  while [ $# -gt 0 ]; do
    case "$1" in
      --force) FORCE=1 ;;
      --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

  if ! find_radios; then
    echo "No USB serial ports found: is the radio plugged in and switched on?"
    return 1
  fi
  if [ -z "$number" ]; then
    if [ ${#RADIOS[@]} -gt 1 ]; then
      echo "There are ${#RADIOS[@]} 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 > ${#RADIOS[@]} )); then
    echo "There's no radio $number: \`radio\` lists ${#RADIOS[@]}"
    return 2
  fi
  radio="${RADIOS[number - 1]}"

  # 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
  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."
    (( ! 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
  port="$(port_path "$ID_CAT_PORT")"
  baud="$ID_BAUD"
  card="$(card_name "$radio")"

  echo "Setting up the $name (Hamlib model $model), on $port at $baud baud"
  echo
  if write_rigctld "$name" "$model" "$port" "$baud"; then
    report rigctld "runs as the hampack-rigctld user service, on $RIGCTLD_ADDR"
  else
    report rigctld "couldn't start: see \`systemctl --user status hampack-rigctld\`"
  fi
  [[ "$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
  else
    report WSJT-X "not installed"
  fi
  if [ -x "$HOME/.local/bin/JS8Call" ]; then
    configure_qt_app JS8Call "$JS8CALL_CONF" JS8Call
  else
    report JS8Call "not installed"
  fi
  configure_pat
  configure_fldigi
  configure_direwolf "$card"

  mkdir -p "$HAMPACK_STATE" &&
    printf 'name=%s\nhamlib=%s\nport=%s\nbaud=%s\ncard=%s\n' "$name" "$model" "$port" "$baud" "$card" > "$HAMPACK_STATE/radio"

  echo
  if [ -n "$card" ]; then
    echo "Choose the radio's sound card in each program yourself: $card, \"$(attr "${CARD_USB[$(card_of "$radio")]}" product)\"."
  else
    echo "No sound card was found with the radio: choose the one it's connected to in each program yourself."
  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
