#!/usr/bin/env bash
set -euo pipefail

log() {
  echo
  echo "==> $*"
}

warn() {
  echo "warning: $*" >&2
}

die() {
  echo "error: $*" >&2
  exit 1
}

have_command() {
  command -v "$1" >/dev/null 2>&1
}

require_command() {
  have_command "$1" || die "missing required command: $1; run step 00 first"
}

require_root() {
  if [[ "${EUID:-$(id -u)}" -ne 0 ]]; then
    die "step 02 must be run as root"
  fi
}

prompt_reboot() {
  echo
  echo "Step 02 complete. Reboot before running step 03:"
  echo "  sudo reboot"

  if [[ -r /dev/tty ]]; then
    local answer=""
    printf "Reboot now? [y/N] " > /dev/tty
    read -r answer < /dev/tty || true
    case "$answer" in
      y|Y|yes|YES)
        reboot
        ;;
    esac
  fi
}

require_root
require_command stty

AT_PORT="${1:-${AT_PORT:-/dev/ttyUSB2}}"
BAUD="${BAUD:-115200}"
PROVISION_STATE_DIR="${PROVISION_STATE_DIR:-/var/lib/embed/provision}"
GNSS_CONFIG_MARKER="${GNSS_CONFIG_MARKER:-$PROVISION_STATE_DIR/gnss-configured}"

log "Checking modem AT port"
if [[ -f "$GNSS_CONFIG_MARKER" ]]; then
  echo "AT/GNSS setup already completed: $GNSS_CONFIG_MARKER"
  echo "Remove this marker to force reconfiguration."
  prompt_reboot
  exit 0
fi

if [[ ! -e "$AT_PORT" ]]; then
  echo "Available ttyUSB devices:"
  ls -l /dev/ttyUSB* 2>/dev/null || true
  die "$AT_PORT does not exist; run step 01, reboot, then retry step 02"
fi

ls -l "$AT_PORT"

log "Configuring serial port"
echo "Current serial settings before changes:"
stty -F "$AT_PORT" -a || true

echo "Setting baud rate: $BAUD"
stty -F "$AT_PORT" "$BAUD" || warn "could not set baud rate to $BAUD"

echo "Setting raw mode"
stty -F "$AT_PORT" raw || warn "could not set raw mode"

echo "Disabling echo"
stty -F "$AT_PORT" -echo || warn "could not disable echo"

echo "Disabling hardware flow control if supported"
stty -F "$AT_PORT" -crtscts 2>/dev/null || warn "could not disable hardware flow control; continuing"

echo "Current serial settings after changes:"
stty -F "$AT_PORT" -a || true

log "Starting modem response reader"
cat "$AT_PORT" &
READER_PID=$!
trap 'kill $READER_PID 2>/dev/null || true' EXIT
sleep 0.2

send() {
  echo
  echo ">>> $1"
  printf '%s\r' "$1" > "$AT_PORT"
  sleep 0.6
}

log "Sending GPS modem commands"
send "AT"
send 'AT+QGPSEND'
send 'AT+QGPSCFG="gnssconfig",1'
send 'AT+QGPSCFG="autogps",1'
send 'AT+QGPSCFG="glonassnmeatype",1'
send 'AT+QGPSCFG="galileonmeatype",1'
send 'AT+QGPSCFG="beidounmeatype",1'
send 'AT+QGPSCFG="outport","usbnmea"'
send 'AT+QGPS=1'

log "Reading back modem GPS settings"
send 'AT+QGPSCFG="gnssconfig"'
send 'AT+QGPSCFG="autogps"'
send 'AT+QGPSCFG="outport"'
send 'AT+QGPS?'

sleep 1

install -d -m 0755 "$PROVISION_STATE_DIR"
touch "$GNSS_CONFIG_MARKER"
echo "Marked AT/GNSS setup complete: $GNSS_CONFIG_MARKER"

echo
echo "After reboot, NMEA can usually be checked with:"
echo "  sudo timeout 20 cat /dev/ttyUSB1"

prompt_reboot
