#!/bin/bash
#
# Author   : Gaston Gonzalez
# Date     : 10 March 2024
# Purpose  : Launches a mode using a connected Bluetooth TNC
source /opt/emcomm-tools/bin/et-common

# Use a simple text file to save the state of the last mode selected
MODE_STATUS_FILE="${HOME}/.config/emcomm-tools/et-mode"

QTTERMTCP_CONF_FILE="${HOME}/.config/QtTermTCP.ini"

# List of supported modes of operation
MODE_ID_NONE="none"
MODE_ID_BBS_CLIENT2="bbs-client2" 
MODE_ID_WINLINK_PACKET="winlink-packet" 

BLUETOOTH_TNC_CHECK=$(ps -ef | grep "[r]fcomm connect")
if [[ $? -ne 0 ]]; then
  et-log "No Bluetooth TNC configured."
  exit 1
fi

# Attempt to stop all EmComm Tools services regardless if they are running.
stop_all_services() {
  et-kill-all 
}

exit_on_service_failure() {
  local systemd_unit_name="$1"
  systemctl is-active --user --quiet "${systemd_unit_name}"
  if [ $? -ne 0 ]; then
    et-log "Can't start mode. ${systemd_unit_name} failed to start."
    exit 1
  fi
}

TIMEOUT=15  # Total time to wait in seconds
INTERVAL=2  # Interval between checks in seconds

start_and_wait_for_service() {
  local systemd_unit_name="$1"
  local elapsed=0

  et-log "Starting ${systemd_unit_name}..."
  systemctl --user start ${systemd_unit_name}

  et-log "Waiting for ${systemd_unit_name} to become active..."

  while ! systemctl is-active --user --quiet "${systemd_unit_name}"; do
      sleep "$INTERVAL"
      elapsed=$((elapsed + INTERVAL))
      if [ "$elapsed" -ge "$TIMEOUT" ]; then
          et-log "Timeout reached. ${systemd_unit_name} failed to start."
          exit 1
      fi
      et-log "Waiting for ${systemd_unit_name} to become active..."
  done

  # Some applications even when started still need a bit of extra time to be available. 
  # Add a short think time of 2 seconds. The ARDOP modem requies extra time.
  sleep 2

  # Do one more check to ensure that we are running, otherwise exit.
  exit_on_service_failure ${systemd_unit_name}
}

# Build list of options
options=()
options+=("${MODE_ID_NONE}" "No mode selected")
options+=("${MODE_ID_BBS_CLIENT2}" "BBS Client (QtTermTCP)")
options+=("${MODE_ID_WINLINK_PACKET}" "Winlink over VHF/UHF (AX.25 Packet)")

# Prompt user for option and save exit status
SELECTED_MODE=$(dialog --clear --menu "Select a mode:" 0 0 0 "${options[@]}" 3>&1 1>&2 2>&3)
exit_status=$?

tput sgr 0 && clear

if [ $exit_status -eq 0 ]; then

  stop_all_services

  echo ${SELECTED_MODE} > ${MODE_STATUS_FILE}

  case ${SELECTED_MODE} in
    ${MODE_ID_NONE})
      et-log "No mode selected"
    ;;
    ${MODE_ID_BBS_CLIENT2})
      if [[ -e /dev/rfcomm0 ]]; then
        et-log "Starting KISS over TCP"

        socat -d TCP-LISTEN:8100,reuseaddr,fork FILE:/dev/rfcomm0,raw &
      fi

      if [[ $? -ne 0 ]]; then
        et-log "Can't start QtTermTCP. KISS over TCP failed to start."
        exit 1
      fi

      et-log "Starting QtTermTCP."
      et-qttermtcp start
    ;;
    ${MODE_ID_WINLINK_PACKET})
      KISS_OUT=$(sudo kissattach ${BT_DEVICE} ${AX25_PORT})

      if [ $? -ne 0 ]; then
        echo -e "${RED}Failed to setup KISS for Bluetooth TNC.${NC}"
        exit 1
      fi

      KISS_OUT=$(sudo kissparms -c 1 -p ${AX25_PORT})

      start_and_wait_for_service et-service-winlink-native-packet
      min http://localhost:8080
    ;;
    *)
      et-log "Mode ${SELECTED_MODE} not yet supported"
      exit 1
    ;;
  esac

else
  et-log "No mode selected"
  echo ${MODE_ID_NONE} > ${MODE_STATUS_FILE}
  exit 1
fi
