#!/bin/sh
# Bananarchy GPS reception & coordinate detection CLI utility
# Queries Qualcomm QDSP6 / ModemManager GNSS (gps-nmea + gps-raw + 3gpp-lac-ci).

ACTION="${1:-status}"

enable_gps() {
  mmcli -m any --location-enable-gps-nmea --location-enable-gps-raw >/dev/null 2>&1 || true
  mmcli -m any --location-set-gps-refresh-rate=2 >/dev/null 2>&1 || true
}

disable_gps() {
  mmcli -m any --location-disable-gps-nmea --location-disable-gps-raw >/dev/null 2>&1 || true
}

print_status() {
  enable_gps
  RAW="$(mmcli -m any -K --location-get 2>/dev/null)"
  if [ -z "$RAW" ]; then
    echo "GPS Status: Modem not ready"
    exit 1
  fi
  MCC="$(printf '%s\n' "$RAW" | awk -F': ' '/location\.3gpp\.mcc/{print $2}')"
  MNC="$(printf '%s\n' "$RAW" | awk -F': ' '/location\.3gpp\.mnc/{print $2}')"
  TAC="$(printf '%s\n' "$RAW" | awk -F': ' '/location\.3gpp\.tac/{print $2}')"
  CID="$(printf '%s\n' "$RAW" | awk -F': ' '/location\.3gpp\.cid/{print $2}')"
  LAT="$(printf '%s\n' "$RAW" | awk -F': ' '/location\.gps\.latitude/{print $2}')"
  LON="$(printf '%s\n' "$RAW" | awk -F': ' '/location\.gps\.longitude/{print $2}')"
  ALT="$(printf '%s\n' "$RAW" | awk -F': ' '/location\.gps\.altitude/{print $2}')"
  UTC="$(printf '%s\n' "$RAW" | awk -F': ' '/location\.gps\.utc/{print $2}')"
  echo "=== Bananarchy GNSS / GPS Reception Status ==="
  echo "3GPP Cell : MCC=${MCC:--} MNC=${MNC:--} TAC=${TAC:--} CID=${CID:--}"
  echo "GPS Fix   : Lat=${LAT:---} Lon=${LON:---} Alt=${ALT:---}m UTC=${UTC:---}"
  echo "--- NMEA Sentences ---"
  printf '%s\n' "$RAW" | awk -F': ' '/location\.gps\.nmea\.value/{print $2}'
}

case "$ACTION" in
  enable)
    enable_gps
    echo "GPS enabled (2s refresh)"
    ;;
  disable)
    disable_gps
    echo "GPS disabled"
    ;;
  nmea)
    enable_gps
    mmcli -m any -K --location-get 2>/dev/null | awk -F': ' '/location\.gps\.nmea\.value/{print $2}'
    ;;
  watch)
    enable_gps
    while true; do
      clear
      print_status
      sleep 2
    done
    ;;
  gui|open)
    exec xgps
    ;;
  status|test|*)
    print_status
    ;;
esac
