#!/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 01 must be run as root"
  fi
}

prompt_reboot() {
  echo
  echo "Step 01 complete. Reboot before running step 02:"
  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 lsusb
require_command systemctl
require_command mmcli
require_command nmcli

QUECTEL_USB_ID="${QUECTEL_USB_ID:-2c7c:0125}"
QUECTEL_USB_NAME="${QUECTEL_USB_NAME:-Quectel Wireless Solutions Co., Ltd.}"
GSM_CONNECTION_NAME="${GSM_CONNECTION_NAME:-4G}"
GSM_APN="${GSM_APN:-telstra.m2m}"

log "Checking USB modem"
if lsusb -d "$QUECTEL_USB_ID" >/dev/null 2>&1; then
  echo "Found expected USB modem:"
  lsusb -d "$QUECTEL_USB_ID"
else
  warn "expected USB modem not found: $QUECTEL_USB_ID $QUECTEL_USB_NAME"
  echo "All USB devices:"
  lsusb || true
  warn "continue only if the modem is intentionally absent or appears under a different ID"
fi

log "Enabling ModemManager"
systemctl enable ModemManager >/dev/null 2>&1 || warn "could not enable ModemManager"

if systemctl is-active --quiet ModemManager; then
  echo "ModemManager is active"
else
  echo "Starting ModemManager"
  systemctl start ModemManager || warn "could not start ModemManager"
fi

systemctl status ModemManager --no-pager || true

log "Checking ModemManager modem inventory"
mmcli_out=""
if mmcli_out="$(mmcli -L 2>&1)"; then
  echo "$mmcli_out"
else
  warn "mmcli -L failed"
  echo "$mmcli_out"
fi

modem_index=""
while IFS= read -r line; do
  if [[ "$line" =~ /Modem/([0-9]+) ]]; then
    modem_index="${BASH_REMATCH[1]}"
    break
  fi
done <<< "$mmcli_out"

if [[ -n "$modem_index" ]]; then
  echo
  echo "Details for modem $modem_index:"
  mmcli -m "$modem_index" || true
else
  warn "no ModemManager modem found yet; reboot may be required"
fi

log "Configuring NetworkManager GSM connection"
if nmcli -g NAME connection show "$GSM_CONNECTION_NAME" >/dev/null 2>&1; then
  echo "Connection already exists: $GSM_CONNECTION_NAME"
else
  echo "Adding GSM connection: $GSM_CONNECTION_NAME"
  nmcli connection add type gsm ifname "*" con-name "$GSM_CONNECTION_NAME" apn "$GSM_APN"
fi

echo "Ensuring GSM connection settings"
nmcli connection modify "$GSM_CONNECTION_NAME" \
  gsm.apn "$GSM_APN" \
  connection.autoconnect yes \
  connection.autoconnect-priority -999

echo "Active NetworkManager connections:"
nmcli connection show --active || true

prompt_reboot
