#!/bin/bash
#
# Author  : Gaston Gonzalez
# Date    : 2 October 2025
# Purpose : Wrapper script for starting fldigi with PnP support
#
# Preconditions
# 1. Supported radio and audio interface are connected and properly detected
#
# Postconditions
# 1. Stop all running EmComm Tools modes
# 2. fldigi core settings updated (e.g., CAT, audio, user config and ETC defaults)
# 3. fldigi started

usage() {
  echo "usage: $(basename $0) <command>"
  echo "  start           - Update config and start fldigi"
  echo "  update-config   - Update config"
}

if [[ $# -ne 1 ]]; then
  usage
  exit 1
fi

notify_user() {
  notify-send \
   -t 5000 \
   --app-name="EmComm Tools" \
   "$1"
}

start() {
  /opt/emcomm-tools/bin/et-kill-all && update-config && /usr/local/bin/fldigi &
}

update-config () {

    # 1. Check if the audio symlink was created by the udev rules
    if [[ -e /dev/et-audio ]]; then

       # 2. Check that this device was properly tagged with the ET_AUDIO env variable 
       APLAY_OUT=$(arecord -l | grep ET_AUDIO)
       if [[ $? -eq 0 ]]; then

         ## Configure ALSA settings for sound card
         /opt/emcomm-tools/bin/et-audio update-config

       else
         et-log "No ET_AUDIO device detected."
         notify_user "Can't start fldigi. No ET_AUDIO device detected."
         exit 1
       fi
    else
      et-log "No ET_AUDIO device plugged in."
      notify_user "Can't start fldigi. No supported audio device plugged in."
      exit 1
    fi
}

case $1 in
  start)
    start
    ;;
  update-config)
    update-config
    ;;
  *)
    echo "Invalid command."
    usage
    exit 1
  ;;
esac
