#!/bin/bash
#
# Author  : Gaston Gonzalez
# Date    : 4 November 2024
# Updated : 5 November 2024
# Purpose : Wrapper script for starting YAAC with PnP support
#
# Preconditions:
# 1. Supported radio and audio interface are connected and properly detected
# 2. Appropriate modem is started: Dire Wolf (et-direwolf) or ARDOP (et-ardop). 
#
# Postconditions:
# 1. Callsign, Winlink  password, and grid are updated are updated 
# 2. pat http is started

PAT_CONF_FILE=${HOME}/.config/pat/config.json
PAT_CONF_FILE_TEMPLATE=/etc/skel/.config/pat/config.json

usage() {
  echo "usage: $(basename $0) <command>"
  echo "  <command>"
  echo "    start-ardop     - Start Pat Winlink in ardop mode"
  echo "    start-packet    - Start Pat Winlink in packet mode"
  echo "    update-config   - Update configuration for selected mode"
}

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

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

start_ardop() {

  ps -ef | grep "[a]rdopcf"
  if [ $? -ne 0 ]; then
    et-log "Can't start Pat in ARDOP mode. ARDOP not running. Run: et-ardop"
    notify_user "ARDOP not running. Run: et-ardop"
    exit 1
  fi

  update_config

  CMD="pat http"
  et-log "Starting Pat with: ${CMD}"

  ${CMD}
}

start_packet() {
  
  RIGCTLD_OUT=$(ps -ef | grep "[d]irewolf")
  if [ $? -ne 0 ]; then
    et-log "Can't start Pat in packet mode. Dire Wolf not running. Run: et-direwolf simple-packet"
    notify_user "Dire Wolf not running. Run: et-direwolf simple-packet"
    exit 1
  fi

  update_config

  CMD="pat http"
  et-log "Starting Pat with: ${CMD}"

  ${CMD}
}

update_config () {

    [ -z "$ET_USER_CONFIG" ] && ET_USER_CONFIG="${HOME}/.config/emcomm-tools/user.json"

    CALLSIGN=$(cat ${ET_USER_CONFIG} | jq -r .callsign)
    GRID=$(cat ${ET_USER_CONFIG} | jq -r .grid)
    WINLINK_PASSWD=$(cat ${ET_USER_CONFIG} | jq -r .winlinkPasswd)

    if [ "${CALLSIGN}" = "N0CALL" ]; then
      notify_user "Can't start Pat. No callsign set. Run: et-user."
      exit 1
    fi

    et-log "Updating Pat configuration file: ${PAT_CONF_FILE}..."
    cp -v ${PAT_CONF_FILE_TEMPLATE} ${PAT_CONF_FILE}

    sed -i "s|{{ET_CALLSIGN}}|${CALLSIGN}|g" ${PAT_CONF_FILE}
    sed -i "s|{{ET_WINLINK_PASSWD}}|${WINLINK_PASSWD}|g" ${PAT_CONF_FILE}
    sed -i "s|{{ET_GRID}}|${GRID}|g" ${PAT_CONF_FILE}
}

case $1 in
  start-ardop)
    start_ardop
    ;;
  start-packet)
    start_packet
    ;;
  update-config)
    update_config
    ;;
  *)
    echo "Invalid command."
    usage
    exit 1
  ;;
esac
