#!/bin/sh
# Bananarchy Dual-SIM & QMI UIM Provisioning Helper for Qualcomm MSM8905/MSM8909
set -eu

CONF_FILE="/etc/conf.d/msm-modem-uim-selection"
if [ -r "$CONF_FILE" ]; then
  # shellcheck disable=SC1090
  . "$CONF_FILE"
fi

SIM_WAIT_TIME="${SIM_WAIT_TIME:-${sim_wait_time:-4}}"
PREFERRED_SIM_SLOT="${PREFERRED_SIM_SLOT:-${preferred_sim_slot:-1}}"
QMICLI_BIN="${BANANARCHY_QMICLI_BIN:-qmicli}"
QMICLI_MODEM=""

ensure_usb_network_gadget() {
  CONFIGFS="/sys/kernel/config/usb_gadget"
  if ! [ -d "$CONFIGFS" ]; then
    modprobe libcomposite 2>/dev/null || true
    mount -t configfs configfs /sys/kernel/config 2>/dev/null || true
  fi
  udc_dev="$(ls /sys/class/udc 2>/dev/null | head -n 1 || true)"
  if [ -z "$udc_dev" ]; then
    modprobe pm8916-lbc 2>/dev/null || true
    w=0
    while [ -z "$udc_dev" ] && [ "$w" -lt 20 ]; do
      sleep 0.1
      udc_dev="$(ls /sys/class/udc 2>/dev/null | head -n 1 || true)"
      w=$((w + 1))
    done
  fi
  if [ -d "$CONFIGFS" ] && [ -n "$udc_dev" ]; then
    if ! [ -d "$CONFIGFS/g1" ]; then
      mkdir -p "$CONFIGFS/g1" 2>/dev/null || true
      echo "0x18D1" > "$CONFIGFS/g1/idVendor" 2>/dev/null || true
      echo "0xD001" > "$CONFIGFS/g1/idProduct" 2>/dev/null || true
      mkdir -p "$CONFIGFS/g1/strings/0x409" 2>/dev/null || true
      echo "Nokia" > "$CONFIGFS/g1/strings/0x409/manufacturer" 2>/dev/null || true
      echo "Bananarchy" > "$CONFIGFS/g1/strings/0x409/serialnumber" 2>/dev/null || true
      echo "Nokia 8110 4G" > "$CONFIGFS/g1/strings/0x409/product" 2>/dev/null || true
      func="ncm.usb0"
      if ! mkdir -p "$CONFIGFS/g1/functions/$func" 2>/dev/null; then
        func="rndis.usb0"
        mkdir -p "$CONFIGFS/g1/functions/$func" 2>/dev/null || true
      fi
      mkdir -p "$CONFIGFS/g1/configs/c.1/strings/0x409" 2>/dev/null || true
      echo "USB network" > "$CONFIGFS/g1/configs/c.1/strings/0x409/configuration" 2>/dev/null || true
      ln -sf "$CONFIGFS/g1/functions/$func" "$CONFIGFS/g1/configs/c.1/" 2>/dev/null || true
    fi
    cur_udc="$(cat "$CONFIGFS/g1/UDC" 2>/dev/null | tr -d '[:space:]' || true)"
    if [ -z "$cur_udc" ]; then
      echo "$udc_dev" > "$CONFIGFS/g1/UDC" 2>/dev/null || true
    fi
  fi
  if ip link show dev usb0 >/dev/null 2>&1; then
    ip link set usb0 up 2>/dev/null || true
    ip -4 addr show dev usb0 2>/dev/null | grep -q "172.16.42.1" || \
      ip addr add 172.16.42.1/16 dev usb0 2>/dev/null || true
    if ! pidof unudhcpd >/dev/null 2>&1; then
      (unudhcpd -i usb0 -s 172.16.42.1 -c 172.16.42.2 >/dev/null 2>&1) &
    fi
  fi
}

detect_qmicli_modem() {
  if [ -n "${BANANARCHY_QMICLI_BIN:-}" ] && [ -x "$BANANARCHY_QMICLI_BIN" ]; then
    QMICLI_MODEM="$BANANARCHY_QMICLI_BIN"
    return 0
  fi
  if ! command -v "$QMICLI_BIN" >/dev/null 2>&1; then
    return 1
  fi
  if [ -e "/dev/wwan0qmi0" ]; then
    if timeout 3 "$QMICLI_BIN" --silent -pd /dev/wwan0qmi0 --device-open-qmi --uim-noop >/dev/null 2>&1; then
      QMICLI_MODEM="timeout 4 $QMICLI_BIN --silent -pd /dev/wwan0qmi0 --device-open-qmi"
      return 0
    elif timeout 3 "$QMICLI_BIN" --silent -d /dev/wwan0qmi0 --device-open-qmi --uim-noop >/dev/null 2>&1; then
      QMICLI_MODEM="timeout 4 $QMICLI_BIN --silent -d /dev/wwan0qmi0 --device-open-qmi"
      return 0
    fi
  fi
  if timeout 3 "$QMICLI_BIN" --silent -d qrtr://0 --uim-noop >/dev/null 2>&1; then
    QMICLI_MODEM="timeout 4 $QMICLI_BIN --silent -d qrtr://0"
    return 0
  elif timeout 3 "$QMICLI_BIN" --silent -pd qrtr://0 --uim-noop >/dev/null 2>&1; then
    QMICLI_MODEM="timeout 4 $QMICLI_BIN --silent -pd qrtr://0"
    return 0
  elif [ -e "/dev/modem" ]; then
    if timeout 3 "$QMICLI_BIN" --silent -pd /dev/modem --uim-noop >/dev/null 2>&1; then
      QMICLI_MODEM="timeout 4 $QMICLI_BIN --silent -pd /dev/modem"
      return 0
    elif timeout 3 "$QMICLI_BIN" --silent -d /dev/modem --uim-noop >/dev/null 2>&1; then
      QMICLI_MODEM="timeout 4 $QMICLI_BIN --silent -d /dev/modem"
      return 0
    fi
  fi
  return 1
}

wait_for_qmicli_modem() {
  max_wait="${1:-12}"
  count=0
  while [ "$count" -lt "$max_wait" ]; do
    if detect_qmicli_modem; then
      return 0
    fi
    sleep 1
    count=$((count + 1))
  done
  return 1
}

# Parse `qmicli --uim-get-card-status` into shell-safe KEY=VALUE lines
parse_uim_card_status() {
  raw_status="$1"
  pref_slot="$2"
  printf "%s\n" "$raw_status" | awk -v pref="$pref_slot" '
    BEGIN {
      prim_slot = 0
      prim_app = 0
      sec_slot = 0
      sec_app = 0
      cur_slot = 0
      in_app = 0
      for (s = 1; s <= 2; s++) {
        cstate[s] = "absent"
        rawstate[s] = "absent"
        upin_state[s] = "not-initialized"
        upin_ret[s] = 0
        upuk_ret[s] = 0
        app_type[s] = "none"
        app_state[s] = "none"
        aid[s] = ""
        pin1_state[s] = "not-initialized"
        pin1_ret[s] = 0
        puk1_ret[s] = 0
        want_aid[s] = 0
        need_aid_line[s] = 0
      }
    }
    /Primary GW:/ {
      if ($0 ~ /slot \x27[0-9]+\x27/) {
        line = $0
        sub(/.*slot \x27/, "", line)
        sub(/\x27.*/, "", line)
        prim_slot = line + 0
      }
      if ($0 ~ /application \x27[0-9]+\x27/) {
        line = $0
        sub(/.*application \x27/, "", line)
        sub(/\x27.*/, "", line)
        prim_app = line + 0
      }
    }
    /Secondary GW:/ {
      if ($0 ~ /slot \x27[0-9]+\x27/) {
        line = $0
        sub(/.*slot \x27/, "", line)
        sub(/\x27.*/, "", line)
        sec_slot = line + 0
      }
      if ($0 ~ /application \x27[0-9]+\x27/) {
        line = $0
        sub(/.*application \x27/, "", line)
        sub(/\x27.*/, "", line)
        sec_app = line + 0
      }
    }
    /^[[:space:]]*Slot \[[0-9]+\]:/ {
      line = $0
      sub(/.*Slot \[/, "", line)
      sub(/\].*/, "", line)
      cur_slot = line + 0
      in_app = 0
      next
    }
    cur_slot >= 1 && cur_slot <= 2 {
      if ($0 ~ /^[[:space:]]*Application \[[0-9]+\]:/) {
        in_app = 1
        next
      }
      if (!in_app && $0 ~ /Card state:/) {
        line = $0
        sub(/.*Card state:[[:space:]]*\x27/, "", line)
        sub(/\x27.*/, "", line)
        rawstate[cur_slot] = line
        if (line == "present") cstate[cur_slot] = "present"
        else if (line == "absent" || line ~ /no-atr-received/) cstate[cur_slot] = "absent"
        else cstate[cur_slot] = "error"
      }
      if (!in_app && $0 ~ /UPIN state:/) {
        line = $0
        sub(/.*UPIN state:[[:space:]]*\x27/, "", line)
        sub(/\x27.*/, "", line)
        upin_state[cur_slot] = line
      }
      if (!in_app && $0 ~ /UPIN retries:/) {
        line = $0
        sub(/.*UPIN retries:[[:space:]]*\x27/, "", line)
        sub(/\x27.*/, "", line)
        upin_ret[cur_slot] = line + 0
      }
      if (!in_app && $0 ~ /UPUK retries:/) {
        line = $0
        sub(/.*UPUK retries:[[:space:]]*\x27/, "", line)
        sub(/\x27.*/, "", line)
        upuk_ret[cur_slot] = line + 0
      }
      if (in_app && $0 ~ /Application type:/) {
        line = $0
        sub(/.*Application type:[[:space:]]*\x27/, "", line)
        sub(/\x27.*/, "", line)
        if (line ~ /^usim/) {
          app_type[cur_slot] = "usim"
          want_aid[cur_slot] = 2
        } else if (line ~ /^sim/ && app_type[cur_slot] != "usim") {
          app_type[cur_slot] = "sim"
          want_aid[cur_slot] = 1
        } else if (app_type[cur_slot] == "none") {
          app_type[cur_slot] = "sim"
          want_aid[cur_slot] = 1
        } else {
          want_aid[cur_slot] = 0
        }
      }
      if (in_app && $0 ~ /Application state:/ && want_aid[cur_slot] > 0) {
        line = $0
        sub(/.*Application state:[[:space:]]*\x27/, "", line)
        sub(/\x27.*/, "", line)
        app_state[cur_slot] = line
      }
      if (in_app && $0 ~ /Application ID:/ && want_aid[cur_slot] > 0) {
        need_aid_line[cur_slot] = 1
        next
      }
      if (in_app && need_aid_line[cur_slot] == 1) {
        line = $0
        gsub(/^[[:space:]]+|[[:space:]]+$/, "", line)
        if (line != "" && line !~ /:.*\x27/) {
          aid[cur_slot] = line
        }
        need_aid_line[cur_slot] = 0
      }
      if (in_app && $0 ~ /PIN1 state:/ && want_aid[cur_slot] > 0) {
        line = $0
        sub(/.*PIN1 state:[[:space:]]*\x27/, "", line)
        sub(/\x27.*/, "", line)
        pin1_state[cur_slot] = line
      }
      if (in_app && $0 ~ /PIN1 retries:/ && want_aid[cur_slot] > 0) {
        line = $0
        sub(/.*PIN1 retries:[[:space:]]*\x27/, "", line)
        sub(/\x27.*/, "", line)
        pin1_ret[cur_slot] = line + 0
      }
      if (in_app && $0 ~ /PUK1 retries:/ && want_aid[cur_slot] > 0) {
        line = $0
        sub(/.*PUK1 retries:[[:space:]]*\x27/, "", line)
        sub(/\x27.*/, "", line)
        puk1_ret[cur_slot] = line + 0
      }
    }
    END {
      printf "PREFERRED_SLOT=%d\n", (pref == 2 ? 2 : 1)
      printf "PRIMARY_GW_SLOT=%d\n", prim_slot
      printf "PRIMARY_GW_APP=%d\n", prim_app
      printf "SECONDARY_GW_SLOT=%d\n", sec_slot
      printf "SECONDARY_GW_APP=%d\n", sec_app
      for (s = 1; s <= 2; s++) {
        gsub(/[^A-Za-z0-9_.:-]/, "_", cstate[s])
        gsub(/[^A-Za-z0-9_.:-]/, "_", rawstate[s])
        gsub(/[^A-Za-z0-9_.:-]/, "_", app_type[s])
        gsub(/[^A-Za-z0-9_.:-]/, "_", app_state[s])
        gsub(/[^A-Za-z0-9_.:-]/, "", aid[s])
        gsub(/[^A-Za-z0-9_.:-]/, "_", pin1_state[s])
        gsub(/[^A-Za-z0-9_.:-]/, "_", upin_state[s])
        printf "SLOT%d_STATE=%s\n", s, cstate[s]
        printf "SLOT%d_RAW_STATE=%s\n", s, rawstate[s]
        printf "SLOT%d_APP_TYPE=%s\n", s, app_type[s]
        printf "SLOT%d_APP_STATE=%s\n", s, app_state[s]
        printf "SLOT%d_AID=%s\n", s, aid[s]
        printf "SLOT%d_PIN1_STATE=%s\n", s, pin1_state[s]
        printf "SLOT%d_PIN1_RETRIES=%d\n", s, pin1_ret[s]
        printf "SLOT%d_PUK1_RETRIES=%d\n", s, puk1_ret[s]
        printf "SLOT%d_UPIN_STATE=%s\n", s, upin_state[s]
        printf "SLOT%d_UPIN_RETRIES=%d\n", s, upin_ret[s]
        printf "SLOT%d_UPUK_RETRIES=%d\n", s, upuk_ret[s]
      }
    }
  '
}

parse_nas_serving_system() {
  raw_nas="$1"
  printf "%s\n" "$raw_nas" | awk '
    BEGIN {
      reg_state = "unknown"
      cs_state = "unknown"
      ps_state = "unknown"
      rat = ""
      mcc = ""
      mnc = ""
      op_desc = ""
      roam = "off"
      in_rat = 0
      in_plmn = 0
      in_roam = 0
    }
    /^[[:space:]]*Registration state:/ {
      line = $0
      sub(/.*Registration state:[[:space:]]*\x27/, "", line)
      sub(/\x27.*/, "", line)
      reg_state = line
      in_rat = 0; in_plmn = 0; in_roam = 0
      next
    }
    /^[[:space:]]*CS:/ {
      line = $0
      sub(/.*CS:[[:space:]]*\x27/, "", line)
      sub(/\x27.*/, "", line)
      cs_state = line
      next
    }
    /^[[:space:]]*PS:/ {
      line = $0
      sub(/.*PS:[[:space:]]*\x27/, "", line)
      sub(/\x27.*/, "", line)
      ps_state = line
      next
    }
    /^[[:space:]]*Radio interfaces:/ {
      in_rat = 1; in_plmn = 0; in_roam = 0
      next
    }
    /^[[:space:]]*Data service capabilities:/ {
      in_rat = 0
      next
    }
    /^[[:space:]]*Current PLMN:/ {
      in_plmn = 1; in_rat = 0; in_roam = 0
      next
    }
    /^[[:space:]]*Roaming indicators:/ {
      in_roam = 1; in_plmn = 0; in_rat = 0
      next
    }
    /^[[:space:]]*Default roaming status:/ {
      line = $0
      sub(/.*Default roaming status:[[:space:]]*\x27/, "", line)
      sub(/\x27.*/, "", line)
      roam = line
      in_roam = 0
      next
    }
    in_rat && /^[[:space:]]*\[[0-9]+\]:/ {
      line = $0
      sub(/.*\[[0-9]+\]:[[:space:]]*\x27/, "", line)
      sub(/\x27.*/, "", line)
      if (line != "" && line != "none" && rat == "") rat = line
    }
    in_plmn && /MCC:/ {
      line = $0
      sub(/.*MCC:[[:space:]]*\x27/, "", line)
      sub(/\x27.*/, "", line)
      mcc = line
    }
    in_plmn && /MNC:/ {
      line = $0
      sub(/.*MNC:[[:space:]]*\x27/, "", line)
      sub(/\x27.*/, "", line)
      mnc = line
    }
    in_plmn && /Description:/ {
      line = $0
      sub(/.*Description:[[:space:]]*\x27/, "", line)
      sub(/\x27.*/, "", line)
      gsub(/[\r\n\t]/, " ", line)
      op_desc = line
      in_plmn = 0
    }
    in_roam && /^[[:space:]]*\[[0-9]+\]:/ {
      line = $0
      sub(/.*\[[0-9]+\]:[[:space:]]*\x27/, "", line)
      sub(/\x27.*/, "", line)
      if (line == "on") roam = "on"
    }
    END {
      printf "NAS_REG_STATE=%s\n", reg_state
      printf "NAS_CS_STATE=%s\n", cs_state
      printf "NAS_PS_STATE=%s\n", ps_state
      printf "NAS_RAT=%s\n", rat
      printf "NAS_RADIO=%s\n", rat
      printf "NAS_MCC=%s\n", mcc
      printf "NAS_MNC=%s\n", mnc
      printf "NAS_OPERATOR=%s\n", op_desc
      printf "NAS_ROAMING=%s\n", roam
    }
  '
}

save_preferred_slot() {
  target_slot="$1"
  PREFERRED_SIM_SLOT="$target_slot"
  if [ -f "$CONF_FILE" ]; then
    if grep -q "^preferred_sim_slot=" "$CONF_FILE"; then
      sed -i "s/^preferred_sim_slot=.*/preferred_sim_slot=$target_slot/" "$CONF_FILE"
    else
      printf "\npreferred_sim_slot=%s\n" "$target_slot" >> "$CONF_FILE"
    fi
  else
    printf "sim_wait_time=10\npreferred_sim_slot=%s\n" "$target_slot" > "$CONF_FILE"
  fi
}

ensure_dsds_nas_registration() {
  dual_arg="${1:-auto}"
  if ! command -v python3 >/dev/null 2>&1; then
    return 0
  fi
  rat_parked=0
  [ -f "${BANANARCHY_POWER_RUNDIR:-/run/bananarchy-power-policy}/rat_parked" ] && rat_parked=1
  _dsds_file="${BANANARCHY_DSDS_ACTIVE_FILE:-/tmp/sxmo_dsds_active}"
  if [ "$dual_arg" = "1" ] || [ "$dual_arg" = "0" ]; then
    dual_flag="$dual_arg"
  elif [ "${BANANARCHY_DUAL_SIM:-}" = "1" ]; then
    dual_flag="1"
  elif [ "${BANANARCHY_DUAL_SIM:-}" = "0" ]; then
    dual_flag="0"
  elif [ -r "$_dsds_file" ] && [ "$(tr -d ' \r\n' < "$_dsds_file" 2>/dev/null || echo 0)" = "1" ]; then
    dual_flag="1"
  else
    dual_flag="0"
  fi
  python3 - "$dual_flag" "$rat_parked" << 'PY' >/dev/null 2>&1 || true
import os, select, socket, struct, sys, time

dual = (len(sys.argv) > 1 and sys.argv[1] == "1")
rat_parked = (len(sys.argv) > 2 and sys.argv[2] == "1")
mock_sock = os.environ.get("BANANARCHY_QRTR_MOCK_SOCK", "")

AF_QIPCRTR = 42
QRTR_PORT_CTRL = 0xfffffffe
QRTR_TYPE_NEW_SERVER = 4
QRTR_TYPE_NEW_LOOKUP = 10
QMI_SERVICE_NAS = 3
QMI_SERVICE_DSD = 0x2A

MOCK_MAGIC = 0x51525452
MOCK_MSG_LOOKUP = 1
MOCK_MSG_DATA = 3
MOCK_HDR_FMT = "<9I"
MOCK_HDR_SIZE = struct.calcsize(MOCK_HDR_FMT)


class QrtrTransport:
  def __init__(self):
    self.is_mock = bool(mock_sock)
    self.socks = []

  def open_sock(self, svc=QMI_SERVICE_NAS):
    if self.is_mock:
      s = socket.socket(socket.AF_UNIX, socket.SOCK_SEQPACKET)
      s.connect(mock_sock)
      s.send(struct.pack(MOCK_HDR_FMT, MOCK_MAGIC, MOCK_MSG_LOOKUP, 1, 0, 0, 0, svc, 0, 0))
      addr = None
      r, _, _ = select.select([s], [], [], 0.5)
      if r:
        d = s.recv(4096)
        if len(d) >= MOCK_HDR_SIZE:
          magic, _, _, _, _, _, srv, _, plen = struct.unpack_from(MOCK_HDR_FMT, d, 0)
          if magic == MOCK_MAGIC and srv == svc and plen >= 8:
            dn, dp = struct.unpack_from("<II", d, MOCK_HDR_SIZE)
            if dp != 0:
              addr = (dn, dp)
      self.socks.append(s)
      return s, addr
    else:
      ls = socket.socket(AF_QIPCRTR, socket.SOCK_DGRAM)
      node, _ = ls.getsockname()
      ls.sendto(struct.pack("<IIIII", QRTR_TYPE_NEW_LOOKUP, svc, 0, 0, 0), (node, QRTR_PORT_CTRL))
      addr = None
      while True:
        r, _, _ = select.select([ls], [], [], 0.2)
        if not r:
          break
        data, _ = ls.recvfrom(256)
        if len(data) >= 20:
          cmd, srv, inst, srv_node, srv_port = struct.unpack("<IIIII", data[:20])
          if cmd == QRTR_TYPE_NEW_SERVER:
            if srv == svc and srv_port != 0:
              addr = (srv_node, srv_port)
            if srv == 0 and srv_node == 0 and srv_port == 0:
              break
      ls.close()
      if not addr:
        return None, None
      s = socket.socket(AF_QIPCRTR, socket.SOCK_DGRAM)
      self.socks.append(s)
      return s, addr

  def qmi_req(self, s, addr, txn, msg_id, tlvs=b"", svc=QMI_SERVICE_NAS):
    if not s or not addr:
      return b""
    qmi_pkt = struct.pack("<BHHH", 0x00, txn, msg_id, len(tlvs)) + tlvs
    if self.is_mock:
      hdr = struct.pack(MOCK_HDR_FMT, MOCK_MAGIC, MOCK_MSG_DATA, 1, 0, addr[0], addr[1], svc, 0, len(qmi_pkt))
      s.send(hdr + qmi_pkt)
    else:
      s.sendto(qmi_pkt, addr)
    for _ in range(12):
      r, _, _ = select.select([s], [], [], 0.3)
      if not r:
        return b""
      raw = s.recv(4096) if self.is_mock else s.recvfrom(4096)[0]
      if self.is_mock:
        if len(raw) < MOCK_HDR_SIZE:
          continue
        magic, _, _, _, _, _, _, _, plen = struct.unpack_from(MOCK_HDR_FMT, raw, 0)
        if magic != MOCK_MAGIC:
          continue
        resp = raw[MOCK_HDR_SIZE:MOCK_HDR_SIZE + plen]
      else:
        resp = raw
      if len(resp) >= 7 and resp[0] == 0x02:
        r_txn, r_msg, _ = struct.unpack("<HHH", resp[1:7])
        if r_txn == txn and r_msg == msg_id:
          return resp
    return b""

  def close(self):
    for s in self.socks:
      try:
        s.close()
      except OSError:
        pass


def parse_tlvs(resp):
  res = {}
  pos = 7
  while pos + 3 <= len(resp):
    tt, tl = struct.unpack("<BH", resp[pos:pos + 3])
    pos += 3
    if pos + tl > len(resp):
      break
    res[tt] = resp[pos:pos + tl]
    pos += tl
  return res


def get_serving_info(tr, s, addr, txn):
  tlvs = parse_tlvs(tr.qmi_req(s, addr, txn, 0x0024))
  v = tlvs.get(0x01, b"")
  if len(v) >= 3:
    return v[0], v[1], v[2]
  if len(v) >= 1:
    return v[0], 0, 0
  return 0, 0, 0


def get_sys_sel_pref(tr, s, addr, txn):
  tlvs = parse_tlvs(tr.qmi_req(s, addr, txn, 0x0034))
  mode_pref = struct.unpack("<H", tlvs[0x11][:2])[0] if 0x11 in tlvs and len(tlvs[0x11]) >= 2 else -1
  srv_dom = struct.unpack("<I", tlvs[0x18][:4])[0] if 0x18 in tlvs and len(tlvs[0x18]) >= 4 else -1
  return mode_pref, srv_dom


tr = QrtrTransport()
try:
  # Step A: In Dual-SIM, lock Secondary GW (sub=1) to cs-only (0) + GSM (0x0004)
  # BEFORE promoting Primary GW (sub=0) to cs-ps (2) because DMS is non-simultaneous-cs-ps.
  if dual:
    s1, addr1 = tr.open_sock(QMI_SERVICE_NAS)
    if s1 and addr1:
      tr.qmi_req(s1, addr1, 1, 0x0045, struct.pack("<BHB", 0x01, 1, 1))
      mp1, sd1 = get_sys_sel_pref(tr, s1, addr1, 2)
      if sd1 != 0 or mp1 != 0x0004:
        tlvs1 = (
          struct.pack("<BHH", 0x11, 2, 0x0004) +
          struct.pack("<BHI", 0x18, 4, 0) +
          struct.pack("<BHB", 0x17, 1, 1)
        )
        tr.qmi_req(s1, addr1, 3, 0x0033, tlvs1)
      reg1, _, _ = get_serving_info(tr, s1, addr1, 4)
      if reg1 not in (1, 2):
        tr.qmi_req(s1, addr1, 5, 0x0022, struct.pack("<BHB", 0x01, 1, 1))

  # Step B: Ensure QMI_DSD binds PRIMARY (1) and reports data_enabled=1 without calling 0x004E.
  sd, addr_dsd = tr.open_sock(QMI_SERVICE_DSD)
  if sd and addr_dsd:
    tr.qmi_req(sd, addr_dsd, 1, 0x0027, struct.pack("<BHI", 0x01, 4, 1), svc=QMI_SERVICE_DSD)
    tr.qmi_req(sd, addr_dsd, 2, 0x0034, struct.pack("<BHB", 0x10, 1, 1), svc=QMI_SERVICE_DSD)

  # Step C: Ensure Primary GW (sub=0) allows cs-ps (2) and triggers PS attach.
  s0, addr0 = tr.open_sock(QMI_SERVICE_NAS)
  if s0 and addr0:
    tr.qmi_req(s0, addr0, 1, 0x0045, struct.pack("<BHB", 0x01, 1, 0))
    mp0, sd0 = get_sys_sel_pref(tr, s0, addr0, 2)
    need_set0 = (sd0 != 2) or (not rat_parked and mp0 == 0x0004)
    if need_set0:
      tlvs0 = (
        struct.pack("<BHI", 0x18, 4, 2) +
        struct.pack("<BHB", 0x17, 1, 1)
      )
      if not rat_parked and mp0 == 0x0004:
        tlvs0 += struct.pack("<BHH", 0x11, 2, 0x001c)
      tr.qmi_req(s0, addr0, 3, 0x0033, tlvs0)
    reg0, _, ps0 = get_serving_info(tr, s0, addr0, 4)
    if reg0 not in (1, 2):
      tr.qmi_req(s0, addr0, 5, 0x0022, struct.pack("<BHB", 0x01, 1, 1))
    if ps0 != 1:
      tr.qmi_req(s0, addr0, 6, 0x0023, struct.pack("<BHB", 0x10, 1, 1))
finally:
  tr.close()
PY
}

run_wds_qmicli() {
  _wds_preload=""
  if [ -n "${BANANARCHY_WDS_BIND_LIB:-}" ]; then
    _wds_preload="$BANANARCHY_WDS_BIND_LIB"
  elif [ -z "${BANANARCHY_QMICLI_BIN:-}" ] && [ -r /usr/lib/libmm-wds-bind.so ]; then
    _wds_preload="/usr/lib/libmm-wds-bind.so"
  fi
  if [ -n "$_wds_preload" ] && [ -r "$_wds_preload" ]; then
    LD_PRELOAD="${_wds_preload}${LD_PRELOAD:+:$LD_PRELOAD}" $QMICLI_MODEM "$@"
  else
    $QMICLI_MODEM "$@"
  fi
}

sync_wds_apn() {
  target_apn="${1:-}"
  target_user="${2:-}"
  target_pass="${3:-}"
  nm_dir="${BANANARCHY_NM_CONNECTIONS_DIR:-/etc/NetworkManager/system-connections}"
  has_explicit=0
  [ -n "$target_apn" ] && has_explicit=1

  if [ -z "$target_apn" ] && [ -d "$nm_dir" ]; then
    for nmf in "$nm_dir"/*.nmconnection; do
      [ -r "$nmf" ] || continue
      if grep -q '^type=gsm$' "$nmf" 2>/dev/null; then
        nm_apn="$(awk -F= '/^\[/{s=$0} s=="[gsm]" && $1=="apn"{print $2; exit}' "$nmf" 2>/dev/null | tr -d '\r"' || true)"
        nm_user="$(awk -F= '/^\[/{s=$0} s=="[gsm]" && $1=="username"{print $2; exit}' "$nmf" 2>/dev/null | tr -d '\r"' || true)"
        nm_pass="$(awk -F= '/^\[/{s=$0} s=="[gsm]" && $1=="password"{print $2; exit}' "$nmf" 2>/dev/null | tr -d '\r"' || true)"
        if [ -n "$nm_apn" ]; then
          target_apn="$nm_apn"
          [ -z "$target_user" ] && target_user="$nm_user"
          [ -z "$target_pass" ] && target_pass="$nm_pass"
          has_explicit=1
          break
        fi
      fi
    done
  fi

  if [ -z "$target_apn" ] && detect_qmicli_modem; then
    _nas_out="$($QMICLI_MODEM --nas-get-serving-system 2>/dev/null || true)"
    if [ -n "$_nas_out" ]; then
      eval "$(parse_nas_serving_system "$_nas_out" 2>/dev/null || true)"
      case "${NAS_MCC:-}${NAS_MNC:-}" in
        25501|25502|25503|25506|2551|2552|2553|2556) target_apn="internet" ;;
      esac
    fi
  fi

  [ -n "$target_apn" ] || return 0
  detect_qmicli_modem || return 0
  prof_list="$(run_wds_qmicli --wds-get-profile-list=3gpp 2>/dev/null || true)"
  [ -n "$prof_list" ] || return 0
  attach_pdn="$(run_wds_qmicli --wds-get-lte-attach-pdn-list 2>/dev/null | sed -n "s/.*Current list:[[:space:]]*'\([^']*\)'.*/\1/p" | head -n1 | awk -F',' '{print $1}' | tr -dc '0-9' || true)"
  def_prof="$(run_wds_qmicli --wds-get-default-profile-number=3gpp 2>/dev/null | sed -n "s/.*Default profile number:[[:space:]]*'\([^']*\)'.*/\1/p" | head -n1 | tr -dc '0-9' || true)"

  target_ids=""
  has_prof1=""
  printf '%s\n' "$prof_list" | grep -q '^[[:space:]]*\[1\][[:space:]]*3gpp' && has_prof1="1"
  for idx in "$attach_pdn" "$def_prof" "$has_prof1"; do
    case "$idx" in ''|*[!0-9]*) continue ;; esac
    case " $target_ids " in *" $idx "*) ;; *) target_ids="$target_ids $idx" ;; esac
  done
  [ -n "$target_ids" ] || return 0

  auth_opts=""
  if [ -n "$target_user" ] && [ -n "$target_pass" ]; then
    auth_opts=",auth=PAP,username=$target_user,password=$target_pass"
  elif [ -n "$target_user" ]; then
    auth_opts=",username=$target_user"
  fi

  SYNC_WDS_CHANGED=0
  for idx in $target_ids; do
    cur_apn="$(printf '%s\n' "$prof_list" | awk -v id="$idx" '
      $0 ~ "\\[" id "\\]" { in_blk=1; next }
      in_blk && /^[[:space:]]*\[[0-9]+\]/ { exit }
      in_blk && /APN:/ {
        line=$0
        sub(/.*APN:[[:space:]]*\x27/, "", line)
        sub(/\x27.*/, "", line)
        print line
        exit
      }
    ' || true)"
    case "$(printf '%s' "$cur_apn" | tr 'A-Z' 'a-z')" in
      ims|sos) continue ;;
    esac
    if [ "$has_explicit" -eq 0 ] && [ "$idx" != "1" ] && [ -z "$cur_apn" ]; then
      continue
    fi
    if [ "$cur_apn" != "$target_apn" ] || [ -n "$auth_opts" ]; then
      run_wds_qmicli --wds-modify-profile="3gpp,$idx,apn=$target_apn,pdp-type=IPV4V6${auth_opts}" >/dev/null 2>&1 || \
        run_wds_qmicli --wds-modify-profile="3gpp,$idx,apn=$target_apn,pdp-type=IP${auth_opts}" >/dev/null 2>&1 || true
      SYNC_WDS_CHANGED=1
    fi
  done
}

mobile_data_prep() {
  apn="${1:-}"
  user="${2:-}"
  pass="${3:-}"
  _dpm_sh="${BANANARCHY_DPM_SH:-/usr/bin/bananarchy-dpm.sh}"
  _run_dir="${BANANARCHY_RUNDIR:-/run/bananarchy}"
  _dsds_file="${BANANARCHY_DSDS_ACTIVE_FILE:-/tmp/sxmo_dsds_active}"
  _use_mm=0
  if [ "${BANANARCHY_SKIP_MM:-0}" != "1" ] && { [ -z "${BANANARCHY_QMICLI_BIN:-}" ] || [ "${BANANARCHY_USE_MM:-0}" = "1" ]; } && command -v mmcli >/dev/null 2>&1; then
    _use_mm=1
  fi
  if [ "$_use_mm" -eq 1 ] && { [ -z "${BANANARCHY_QMICLI_BIN:-}" ] || [ "${BANANARCHY_USE_MM:-0}" = "1" ]; } && command -v nmcli >/dev/null 2>&1; then
    for _guuid in $(timeout 3 nmcli -t -f UUID,TYPE connection show 2>/dev/null | awk -F: '$2=="gsm"{print $1}' || true); do
      timeout 3 nmcli connection modify "$_guuid" connection.autoconnect no >/dev/null 2>&1 || true
    done
    _qst="$(timeout 2 nmcli -t -f TYPE,STATE device status 2>/dev/null | awk -F: '$1=="gsm"{print $2; exit}' || true)"
    case "$_qst" in
      connecting*) timeout 4 nmcli device disconnect qrtr0 >/dev/null 2>&1 || true ;;
    esac
  fi
  if [ -x "$_dpm_sh" ]; then
    "$_dpm_sh" open >/dev/null 2>&1 || true
  fi
  if [ -f "${BANANARCHY_POWER_RUNDIR:-/run/bananarchy-power-policy}/rat_parked" ] && [ -x /usr/bin/bananarchy-power-policy.sh ]; then
    /usr/bin/bananarchy-power-policy.sh unpark-rat >/dev/null 2>&1 || true
  fi
  if detect_qmicli_modem; then
    $QMICLI_MODEM --dms-set-operating-mode=online >/dev/null 2>&1 || true
  fi
  if [ "$_use_mm" -eq 1 ]; then
    _mi=0
    _restarted_mm=0
    while [ "$_mi" -lt 45 ]; do
      if timeout 2 mmcli -L 2>/dev/null | grep -q '/Modem/'; then
        _mm_st_pre="$(timeout 3 mmcli -m any -K 2>/dev/null | awk -F':[[:space:]]*' '/^modem\.generic\.state[[:space:]]*:/ {print $2; exit}' | tr -d ' \r' || true)"
        if [ "$_mm_st_pre" = "failed" ] && [ "$_restarted_mm" -eq 0 ]; then
          _restarted_mm=1
          restart_modemmanager_clean
          _mi=0
          sleep 1
          continue
        fi
        if [ "$_mm_st_pre" = "disabled" ]; then
          timeout 5 mmcli -m any -e >/dev/null 2>&1 || true
        fi
        break
      elif [ "$_mi" -eq 24 ] && [ "$_restarted_mm" -eq 0 ]; then
        _restarted_mm=1
        restart_modemmanager_clean
      fi
      sleep 0.5
      _mi=$((_mi + 1))
    done
  fi
  _did_mode_change=0
  ensure_dsds_nas_registration auto
  if detect_qmicli_modem; then
    _ssp_out="$($QMICLI_MODEM --nas-get-system-selection-preference 2>/dev/null || true)"
    if printf '%s\n' "$_ssp_out" | grep -q "Service domain preference: 'cs-only'"; then
      QMI_CARDS="$($QMICLI_MODEM --uim-get-card-status 2>/dev/null || true)"
      if [ -n "$QMI_CARDS" ]; then
        eval "$(parse_uim_card_status "$QMI_CARDS" "$PREFERRED_SIM_SLOT")"
        if [ "${SECONDARY_GW_SLOT:-0}" = "1" ] || [ "${SECONDARY_GW_SLOT:-0}" = "2" ]; then
          eval "_sec_aid=\${SLOT${SECONDARY_GW_SLOT}_AID:-}"
          mkdir -p "$_run_dir" 2>/dev/null || true
          printf 'SLOT=%s\nAID=%s\n' "$SECONDARY_GW_SLOT" "$_sec_aid" > "$_run_dir/dsds_paused_for_data" 2>/dev/null || true
          $QMICLI_MODEM --uim-change-provisioning-session='activate=no,session-type=secondary-gw-provisioning' >/dev/null 2>&1 || true
          printf '0\n' > "$_dsds_file" 2>/dev/null || true
          ensure_dsds_nas_registration 0
          _did_mode_change=1
        fi
      fi
    fi
  fi
  SYNC_WDS_CHANGED=0
  sync_wds_apn "$apn" "$user" "$pass"
  if [ "${SYNC_WDS_CHANGED:-0}" = "1" ]; then
    ensure_dsds_nas_registration auto
    _did_mode_change=1
  fi
  if detect_qmicli_modem; then
    _w=0
    while [ "$_w" -lt 45 ]; do
      _nas_ok=0
      _dsd_ok=1
      _mm_ok=1
      _nm_ok=1
      _nas_out="$($QMICLI_MODEM --nas-get-serving-system 2>/dev/null || true)"
      eval "$(parse_nas_serving_system "$_nas_out" 2>/dev/null || true)"
      [ "${NAS_PS_STATE:-}" = "attached" ] && _nas_ok=1
      if [ -z "${BANANARCHY_QMICLI_BIN:-}" ]; then
        _dsd_out="$($QMICLI_MODEM --dsd-get-system-status 2>/dev/null || true)"
        if printf '%s\n' "$_dsd_out" | grep -q 'Available data systems retrieved:' && \
           ! printf '%s\n' "$_dsd_out" | grep -Eq "RAT:[[:space:]]*'3gpp-(lte|wcdma|geran|tdscdma|5g)"; then
          _dsd_ok=0
        fi
      fi
      if [ "$_use_mm" -eq 1 ]; then
        _mm_ok=0
        _mm_kv="$(timeout 3 mmcli -m any -K 2>/dev/null || true)"
        _mm_st="$(printf '%s\n' "$_mm_kv" | awk -F':[[:space:]]*' '/^modem\.generic\.state[[:space:]]*:/ {print $2; exit}' | tr -d ' \r')"
        _mm_ps="$(printf '%s\n' "$_mm_kv" | awk -F':[[:space:]]*' '/^modem\.3gpp\.packet-service-state[[:space:]]*:/ {print $2; exit}' | tr -d ' \r')"
        case "$_mm_st" in
          disabled)
            timeout 5 mmcli -m any -e >/dev/null 2>&1 || true
            ;;
          enabled)
            timeout 4 mmcli -m any --3gpp-register-home >/dev/null 2>&1 || true
            ;;
          registered|connected)
            if [ "$_mm_ps" = "attached" ]; then
              _mm_ok=1
            fi
            ;;
        esac
        if command -v nmcli >/dev/null 2>&1; then
          _nm_line="$(timeout 2 nmcli -t -f TYPE,STATE device status 2>/dev/null | grep '^gsm:' | head -n1 || true)"
          case "$_nm_line" in
            ""|*:unavailable|*:unmanaged) _nm_ok=0 ;;
          esac
        fi
      fi
      if [ "$_nas_ok" -eq 1 ] && [ "$_dsd_ok" -eq 1 ] && [ "$_mm_ok" -eq 1 ] && [ "$_nm_ok" -eq 1 ]; then
        break
      fi
      sleep 0.5
      _w=$((_w + 1))
    done
    if [ "$_did_mode_change" = "1" ]; then
      sleep 1
    fi
  fi
}

restore_dsds() {
  _run_dir="${BANANARCHY_RUNDIR:-/run/bananarchy}"
  _pause_file="$_run_dir/dsds_paused_for_data"
  _dsds_file="${BANANARCHY_DSDS_ACTIVE_FILE:-/tmp/sxmo_dsds_active}"
  [ -r "$_pause_file" ] || return 0
  _slot="$(awk -F= '$1=="SLOT"{print $2; exit}' "$_pause_file" 2>/dev/null | tr -dc '0-9' || true)"
  _aid="$(awk -F= '$1=="AID"{print $2; exit}' "$_pause_file" 2>/dev/null | tr -d ' \r\n' || true)"
  rm -f "$_pause_file" 2>/dev/null || true
  if [ "$_slot" != "1" ] && [ "$_slot" != "2" ]; then
    return 0
  fi
  detect_qmicli_modem || return 0
  ensure_dsds_nas_registration 0
  if [ -n "$_aid" ]; then
    $QMICLI_MODEM --uim-change-provisioning-session="slot=$_slot,activate=yes,session-type=secondary-gw-provisioning,aid=$_aid" >/dev/null 2>&1 || \
      $QMICLI_MODEM --uim-change-provisioning-session="slot=$_slot,activate=yes,session-type=secondary-gw-provisioning" >/dev/null 2>&1 || true
  else
    $QMICLI_MODEM --uim-change-provisioning-session="slot=$_slot,activate=yes,session-type=secondary-gw-provisioning" >/dev/null 2>&1 || true
  fi
  printf '1\n' > "$_dsds_file" 2>/dev/null || true
  ensure_dsds_nas_registration 1
}

provision_slot() {
  req_slot="$1"
  wait_secs="$2"

  if ! wait_for_qmicli_modem "$wait_secs"; then
    echo "No modem available." >&2
    return 2
  fi

  if [ ! -d /sys/class/net/wwan0 ]; then
    if [ -x /usr/bin/bananarchy-dpm.sh ]; then
      /usr/bin/bananarchy-dpm.sh open >/dev/null 2>&1 || true
    else
      $QMICLI_MODEM --dpm-open-port=hw-data-ep-type=bam-dmux,hw-data-ep-iface-number=1,hw-data-rx-id=1,hw-data-tx-id=1 >/dev/null 2>&1 || true
      _w=0
      while [ "$_w" -lt 20 ] && [ ! -d /sys/class/net/wwan0 ]; do
        sleep 0.1
        _w=$((_w + 1))
      done
    fi
  fi

  QMI_CARDS="$($QMICLI_MODEM --uim-get-card-status 2>/dev/null || true)"
  count=0
  while : ; do
    if [ -n "$QMI_CARDS" ]; then
      eval "$(parse_uim_card_status "$QMI_CARDS" "$req_slot")"
      if [ "$SLOT1_STATE" = "present" ] && [ "$SLOT1_APP_TYPE" != "none" ] && [ "$SLOT2_STATE" = "present" ] && [ "$SLOT2_APP_TYPE" != "none" ]; then
        break
      elif [ "$count" -ge 2 ] && { { [ "$SLOT1_STATE" = "present" ] && [ "$SLOT1_APP_TYPE" != "none" ]; } || { [ "$SLOT2_STATE" = "present" ] && [ "$SLOT2_APP_TYPE" != "none" ]; }; }; then
        break
      fi
    fi
    if [ "$count" -ge "$SIM_WAIT_TIME" ]; then
      break
    fi
    sleep 1
    count=$((count + 1))
    QMI_CARDS="$($QMICLI_MODEM --uim-get-card-status 2>/dev/null || true)"
  done

  if [ -z "$QMI_CARDS" ]; then
    echo "No SIM card status returned."
    return 0
  fi

  eval "$(parse_uim_card_status "$QMI_CARDS" "$req_slot")"

  # A PIN/PUK-locked SIM cannot be bound to a provisioning session yet.
  # Prefer the other (ready) slot for the primary GW so the unlocked SIM
  # still registers at boot instead of both subscriptions stalling.
  # xmodem re-runs `boot` after the PIN is entered (verify-pin also calls
  # provision_slot), at which point both slots are provisioned normally.
  _pref_pin_locked=0
  eval "_pref_app_state=\${SLOT${req_slot}_APP_STATE:-none}"
  eval "_pref_pin_state=\${SLOT${req_slot}_PIN1_STATE:-not-initialized}"
  case "$_pref_app_state" in
    pin1|puk1|pin2|puk2|illegal|none) _pref_pin_locked=1 ;;
  esac
  case "$_pref_pin_state" in
    enabled-not-verified|blocked|permanently-blocked) _pref_pin_locked=1 ;;
  esac
  if [ "$_pref_pin_locked" = "1" ]; then
    _alt_slot=1
    [ "$req_slot" = "1" ] && _alt_slot=2
    eval "_alt_state=\${SLOT${_alt_slot}_STATE:-absent}"
    eval "_alt_app_state=\${SLOT${_alt_slot}_APP_STATE:-none}"
    if [ "$_alt_state" = "present" ] && [ "$_alt_app_state" = "ready" ]; then
      echo "Slot $req_slot is PIN-locked; using ready slot $_alt_slot for primary GW"
      req_slot="$_alt_slot"
    fi
  fi

  chosen_slot=""
  chosen_aid=""
  if [ "$req_slot" = "2" ]; then
    if [ "$SLOT2_STATE" = "present" ]; then
      chosen_slot="2"
      chosen_aid="$SLOT2_AID"
    elif [ "$SLOT1_STATE" = "present" ]; then
      chosen_slot="1"
      chosen_aid="$SLOT1_AID"
    fi
  else
    if [ "$SLOT1_STATE" = "present" ]; then
      chosen_slot="1"
      chosen_aid="$SLOT1_AID"
    elif [ "$SLOT2_STATE" = "present" ]; then
      chosen_slot="2"
      chosen_aid="$SLOT2_AID"
    fi
  fi

  if [ -z "$chosen_slot" ]; then
    echo "No SIM detected after $SIM_WAIT_TIME seconds."
    return 0
  fi

  if [ "$chosen_slot" != "$PREFERRED_SIM_SLOT" ]; then
    save_preferred_slot "$chosen_slot"
  fi

  other_slot="2"
  if [ "$chosen_slot" = "2" ]; then
    other_slot="1"
  fi
  eval "chosen_app_state=\$SLOT${chosen_slot}_APP_STATE"
  eval "other_state=\$SLOT${other_slot}_STATE"
  eval "other_aid=\$SLOT${other_slot}_AID"
  eval "other_app_state=\$SLOT${other_slot}_APP_STATE"

  need_prim=1
  if [ "$PRIMARY_GW_SLOT" = "$chosen_slot" ] && [ -n "$chosen_app_state" ] && [ "$chosen_app_state" != "none" ] && [ "$chosen_app_state" != "illegal" ]; then
    need_prim=0
  fi

  if [ "$need_prim" = "1" ]; then
    if [ "${SECONDARY_GW_SLOT:-0}" != "0" ]; then
      $QMICLI_MODEM --uim-change-provisioning-session='activate=no,session-type=secondary-gw-provisioning' >/dev/null 2>&1 || true
      SECONDARY_GW_SLOT=0
    fi
    if [ "$PRIMARY_GW_SLOT" != "0" ]; then
      $QMICLI_MODEM --uim-change-provisioning-session='activate=no,session-type=primary-gw-provisioning' >/dev/null 2>&1 || true
    fi
    sleep 0.2
    if [ -n "$chosen_aid" ]; then
      echo "Selecting AID $chosen_aid on slot $chosen_slot (primary-gw-provisioning)"
      if ! $QMICLI_MODEM --uim-change-provisioning-session="slot=$chosen_slot,activate=yes,session-type=primary-gw-provisioning,aid=$chosen_aid" >/dev/null 2>&1; then
        $QMICLI_MODEM --uim-change-provisioning-session="slot=$chosen_slot,activate=yes,session-type=primary-gw-provisioning" >/dev/null 2>&1 || true
      fi
    else
      echo "Selecting slot $chosen_slot (primary-gw-provisioning)"
      $QMICLI_MODEM --uim-change-provisioning-session="slot=$chosen_slot,activate=yes,session-type=primary-gw-provisioning" >/dev/null 2>&1 || true
    fi
    sleep 0.2
  else
    echo "Slot $chosen_slot already bound to primary-gw-provisioning ($chosen_app_state)."
  fi

  # Promote Primary GW (sub=0) to cs-ps before activating secondary-gw-provisioning.
  ensure_dsds_nas_registration 0

  # Dual-SIM Dual Standby (DSDS): provision the second present SIM slot to secondary-gw-provisioning
  if [ "$other_state" = "present" ]; then
    need_sec=1
    if [ "${SECONDARY_GW_SLOT:-0}" = "$other_slot" ] && [ -n "$other_app_state" ] && [ "$other_app_state" != "none" ] && [ "$other_app_state" != "illegal" ]; then
      need_sec=0
    fi
    if [ "$need_sec" = "1" ]; then
      if [ "${SECONDARY_GW_SLOT:-0}" != "0" ] && [ "${SECONDARY_GW_SLOT:-0}" != "$other_slot" ]; then
        $QMICLI_MODEM --uim-change-provisioning-session='activate=no,session-type=secondary-gw-provisioning' >/dev/null 2>&1 || true
      fi
      if [ -n "$other_aid" ]; then
        echo "Selecting AID $other_aid on slot $other_slot (secondary-gw-provisioning)"
        if ! $QMICLI_MODEM --uim-change-provisioning-session="slot=$other_slot,activate=yes,session-type=secondary-gw-provisioning,aid=$other_aid" >/dev/null 2>&1; then
          $QMICLI_MODEM --uim-change-provisioning-session="slot=$other_slot,activate=yes,session-type=secondary-gw-provisioning" >/dev/null 2>&1 || true
        fi
      else
        echo "Selecting slot $other_slot (secondary-gw-provisioning)"
        $QMICLI_MODEM --uim-change-provisioning-session="slot=$other_slot,activate=yes,session-type=secondary-gw-provisioning" >/dev/null 2>&1 || true
      fi
    else
      echo "Slot $other_slot already bound to secondary-gw-provisioning ($other_app_state)."
    fi
  else
    if [ "${SECONDARY_GW_SLOT:-0}" != "0" ]; then
      $QMICLI_MODEM --uim-change-provisioning-session='activate=no,session-type=secondary-gw-provisioning' >/dev/null 2>&1 || true
    fi
  fi
  _dms_mode="$($QMICLI_MODEM --dms-get-operating-mode 2>/dev/null | awk -F"'" '/Mode:/ {print $2; exit}' || true)"
  case "$_dms_mode" in
    low-power|offline|shutting-down|persistent-low-power)
      $QMICLI_MODEM --dms-set-operating-mode=online >/dev/null 2>&1 || true
      ;;
  esac
  if [ "$other_state" = "present" ]; then
    printf '1\n' > /tmp/sxmo_dsds_active 2>/dev/null || true
    ensure_dsds_nas_registration 1
  else
    printf '0\n' > /tmp/sxmo_dsds_active 2>/dev/null || true
    ensure_dsds_nas_registration 0
  fi
  sync_wds_apn "" "" "" || true
  return 0
}

prepare_slot_for_pin_op() {
  req_slot="${1:-1}"
  slot="$req_slot"
  PIN_OP_SESSION="primary-gw-provisioning"
  target_aid=""
  if detect_qmicli_modem; then
    QMI_CARDS="$($QMICLI_MODEM --uim-get-card-status 2>/dev/null || true)"
    if [ -n "$QMI_CARDS" ]; then
      eval "$(parse_uim_card_status "$QMI_CARDS" "$PREFERRED_SIM_SLOT")"
      if [ "$slot" = "1" ] && [ "$SLOT1_STATE" != "present" ] && [ "$SLOT2_STATE" = "present" ]; then
        slot="2"
      elif [ "$slot" = "2" ] && [ "$SLOT2_STATE" != "present" ] && [ "$SLOT1_STATE" = "present" ]; then
        slot="1"
      fi
      eval "target_aid=\$SLOT${slot}_AID"
      if [ "$PRIMARY_GW_SLOT" = "$slot" ]; then
        PIN_OP_SESSION="primary-gw-provisioning"
      elif [ "${SECONDARY_GW_SLOT:-0}" = "$slot" ]; then
        PIN_OP_SESSION="secondary-gw-provisioning"
      elif [ "$PRIMARY_GW_SLOT" != "0" ]; then
        PIN_OP_SESSION="secondary-gw-provisioning"
        if [ -n "$target_aid" ]; then
          $QMICLI_MODEM --uim-change-provisioning-session="slot=$slot,activate=yes,session-type=secondary-gw-provisioning,aid=$target_aid" >/dev/null 2>&1 || \
            $QMICLI_MODEM --uim-change-provisioning-session="slot=$slot,activate=yes,session-type=secondary-gw-provisioning" >/dev/null 2>&1 || true
        else
          $QMICLI_MODEM --uim-change-provisioning-session="slot=$slot,activate=yes,session-type=secondary-gw-provisioning" >/dev/null 2>&1 || true
        fi
        sleep 0.3
      else
        PIN_OP_SESSION="primary-gw-provisioning"
        if [ -n "$target_aid" ]; then
          $QMICLI_MODEM --uim-change-provisioning-session="slot=$slot,activate=yes,session-type=primary-gw-provisioning,aid=$target_aid" >/dev/null 2>&1 || \
            $QMICLI_MODEM --uim-change-provisioning-session="slot=$slot,activate=yes,session-type=primary-gw-provisioning" >/dev/null 2>&1 || true
        else
          $QMICLI_MODEM --uim-change-provisioning-session="slot=$slot,activate=yes,session-type=primary-gw-provisioning" >/dev/null 2>&1 || true
        fi
        sleep 0.3
      fi
    fi
  fi
}

restart_modemmanager_clean() {
  if command -v rc-service >/dev/null 2>&1; then
    timeout 4 rc-service polkit start >/dev/null 2>&1 || true
    timeout 6 rc-service modemmanager restart >/dev/null 2>&1 || {
      killall -q ModemManager 2>/dev/null || true
      sleep 0.3
      timeout 6 rc-service modemmanager zap >/dev/null 2>&1 || true
      timeout 6 rc-service modemmanager start >/dev/null 2>&1 || true
    }
  elif command -v systemctl >/dev/null 2>&1; then
    timeout 6 systemctl restart ModemManager >/dev/null 2>&1 || true
  fi
}

enable_and_register_modem() {
  target_slot="${1:-$PREFERRED_SIM_SLOT}"
  force_unlock="${2:-0}"
  if detect_qmicli_modem; then
    $QMICLI_MODEM --dms-set-operating-mode=online >/dev/null 2>&1 || true
    $QMICLI_MODEM --nas-initiate-network-register >/dev/null 2>&1 || true
  fi

  i=0
  mm_state=""
  while [ "$i" -lt 22 ]; do
    mm_state="$(timeout 3 mmcli -m any -K 2>/dev/null | awk -F': ' '/^modem\.generic\.state / {print $2; exit}' || true)"
    if [ -n "$mm_state" ]; then
      break
    fi
    sleep 1
    i=$((i + 1))
  done

  if [ -z "$mm_state" ] || [ "$mm_state" = "failed" ] || [ "$force_unlock" = "2" ] || { [ "$force_unlock" = "1" ] && [ "$mm_state" = "locked" ]; }; then
    restart_modemmanager_clean
    i=0
    mm_state=""
    while [ "$i" -lt 22 ]; do
      mm_state="$(timeout 3 mmcli -m any -K 2>/dev/null | awk -F': ' '/^modem\.generic\.state / {print $2; exit}' || true)"
      if [ -n "$mm_state" ] && [ "$mm_state" != "failed" ]; then
        break
      fi
      sleep 1
      i=$((i + 1))
    done
  fi

  if [ -z "$mm_state" ] || [ "$mm_state" = "locked" ]; then
    return 0
  fi

  i=0
  while [ "$i" -lt 8 ]; do
    mm_state="$(timeout 3 mmcli -m any -K 2>/dev/null | awk -F': ' '/^modem\.generic\.state / {print $2; exit}' || true)"
    case "$mm_state" in
      disabled)
        timeout 4 mmcli -m any -e >/dev/null 2>&1 || true
        ;;
      enabled)
        timeout 4 mmcli -m any --3gpp-register-home >/dev/null 2>&1 || true
        break
        ;;
      searching|registered|connected|connecting)
        break
        ;;
      locked)
        break
        ;;
    esac
    sleep 1
    i=$((i + 1))
  done

  timeout 4 mmcli -m any --3gpp-register-home >/dev/null 2>&1 || true
  if [ -x /usr/bin/bananarchy-power-policy.sh ]; then
    /usr/bin/bananarchy-power-policy.sh modem-ready >/dev/null 2>&1 || true
  fi
  if command -v sxmo_hook_statusbar.sh >/dev/null 2>&1; then
    DISPLAY="${DISPLAY:-:0}" timeout 3 sxmo_hook_statusbar.sh modem >/dev/null 2>&1 || true
  fi
}

spawn_enable_and_register() {
  s_slot="${1:-$PREFERRED_SIM_SLOT}"
  s_force="${2:-0}"
  (
    exec >/dev/null 2>&1 </dev/null 3>&- 4>&- 5>&- 6>&- 7>&- 8>&- 9>&- 2>/dev/null || true
    enable_and_register_modem "$s_slot" "$s_force"
  ) &
}

cmd="${1:-boot}"

case "$cmd" in
  boot)
    modprobe rpmsg_wwan_ctrl 2>/dev/null || true
    ensure_usb_network_gadget
    if command -v systemd-notify >/dev/null 2>&1; then
      trap '[ $? -eq 0 ] && systemd-notify --ready' EXIT
    fi
    case "$(cat /sys/devices/soc0/machine 2>/dev/null || true)" in
      APQ*)
        echo "Skipping SIM configuration on APQ SoC."
        exit 0
        ;;
    esac
    provision_slot "$PREFERRED_SIM_SLOT" 10 || true
    spawn_enable_and_register "$PREFERRED_SIM_SLOT" 0
    exit 0
    ;;

  status)
    QMI_CARDS=""
    if command -v qmicli >/dev/null 2>&1; then
      if [ -e "/dev/wwan0qmi0" ]; then
        QMI_CARDS="$(timeout 3 qmicli --silent -pd /dev/wwan0qmi0 --device-open-qmi --uim-get-card-status 2>/dev/null || true)"
        if [ -n "$QMI_CARDS" ]; then
          QMICLI_MODEM="timeout 3 qmicli --silent -pd /dev/wwan0qmi0 --device-open-qmi"
        fi
      fi
      if [ -z "$QMI_CARDS" ] && detect_qmicli_modem; then
        QMI_CARDS="$($QMICLI_MODEM --uim-get-card-status 2>/dev/null || true)"
      fi
    fi
    if [ -z "$QMI_CARDS" ]; then
      echo "MODEM_AVAILABLE=0"
      echo "PREFERRED_SLOT=$PREFERRED_SIM_SLOT"
      exit 0
    fi
    echo "MODEM_AVAILABLE=1"
    UIM_KV="$(parse_uim_card_status "$QMI_CARDS" "$PREFERRED_SIM_SLOT")"
    printf "%s\n" "$UIM_KV"
    eval "$UIM_KV"
    QMI_NAS="$($QMICLI_MODEM --nas-get-serving-system 2>/dev/null || true)"
    if [ -n "$QMI_NAS" ]; then
      parse_nas_serving_system "$QMI_NAS"
    fi
    if command -v python3 >/dev/null 2>&1; then
      python3 - "${PRIMARY_GW_SLOT:-0}" "${SECONDARY_GW_SLOT:-0}" "${SLOT1_STATE:-absent}" "${SLOT2_STATE:-absent}" << 'PY' 2>/dev/null || true
import socket, struct, select, sys

prim_slot = int(sys.argv[1]) if len(sys.argv) > 1 and sys.argv[1].isdigit() else 0
sec_slot = int(sys.argv[2]) if len(sys.argv) > 2 and sys.argv[2].isdigit() else 0
s1_state = sys.argv[3] if len(sys.argv) > 3 else "absent"
s2_state = sys.argv[4] if len(sys.argv) > 4 else "absent"

dual_active = 1 if (s1_state == "present" and s2_state == "present" and prim_slot in (1, 2) and sec_slot in (1, 2)) else 0
print(f"DUAL_SIM_ACTIVE={dual_active}")
try:
  with open("/tmp/sxmo_dsds_active", "w") as df:
    df.write(f"{dual_active}\n")
except Exception:
  pass

AF_QIPCRTR = 42
QRTR_PORT_CTRL = 0xfffffffe
QRTR_TYPE_NEW_SERVER = 4
QRTR_TYPE_NEW_LOOKUP = 10

def lookup_srv(sid):
  ls = socket.socket(AF_QIPCRTR, socket.SOCK_DGRAM)
  node, _ = ls.getsockname()
  ls.sendto(struct.pack("<IIIII", QRTR_TYPE_NEW_LOOKUP, sid, 0, 0, 0), (node, QRTR_PORT_CTRL))
  addr = None
  while True:
    r, _, _ = select.select([ls], [], [], 0.12)
    if not r:
      break
    data, _ = ls.recvfrom(256)
    if len(data) >= 20:
      cmd, srv, inst, srv_node, srv_port = struct.unpack("<IIIII", data[:20])
      if cmd == QRTR_TYPE_NEW_SERVER:
        if srv == sid and srv_port != 0:
          addr = (srv_node, srv_port)
        if srv == 0 and srv_node == 0 and srv_port == 0:
          break
  ls.close()
  return addr

def parse_tlvs(resp):
  res = {}
  pos = 7
  while pos + 3 <= len(resp):
    tt, tl = struct.unpack("<BH", resp[pos:pos+3])
    pos += 3
    res[tt] = resp[pos:pos+tl]
    pos += tl
  return res

def qmi_req(s, addr, txn, msg_id, tlvs=b""):
  s.sendto(struct.pack("<BHHH", 0x00, txn, msg_id, len(tlvs)) + tlvs, addr)
  while True:
    r, _, _ = select.select([s], [], [], 0.2)
    if not r:
      return {}
    resp, _ = s.recvfrom(2048)
    if len(resp) >= 7 and resp[0] == 0x02:
      r_txn, r_msg, _ = struct.unpack("<HHH", resp[1:7])
      if r_txn == txn and r_msg == msg_id:
        return parse_tlvs(resp)

nas_addr = lookup_srv(3)
dms_addr = lookup_srv(2)

slot_sub = {}
if prim_slot in (1, 2):
  slot_sub[prim_slot] = 0
if sec_slot in (1, 2):
  slot_sub[sec_slot] = 1

for slot in (1, 2):
  sub = slot_sub.get(slot, -1)
  reg = "not-registered"
  rat = ""
  op = ""
  rssi = ""
  num = ""
  imsi = ""
  if sub >= 0 and nas_addr:
    s = socket.socket(AF_QIPCRTR, socket.SOCK_DGRAM)
    qmi_req(s, nas_addr, 1, 0x0045, struct.pack("<BHB", 0x01, 1, sub))
    si = qmi_req(s, nas_addr, 2, 0x004D)
    for t_id, r_name in ((0x14, "lte"), (0x13, "umts"), (0x12, "gsm")):
      v = si.get(t_id, b"")
      if len(v) >= 1 and v[0] == 2:
        reg = "registered"
        rat = r_name
        break
      elif len(v) >= 1 and v[0] in (1, 3) and reg == "not-registered":
        reg = "searching"
    op_t = qmi_req(s, nas_addr, 3, 0x0039)
    if 0x10 in op_t and len(op_t[0x10]) >= 2:
      slen = op_t[0x10][1]
      op = op_t[0x10][2:2+slen].decode("utf-8", errors="ignore").strip()
    if not op and 0x13 in op_t:
      op = op_t[0x13].decode("utf-8", errors="ignore").strip("\x00 ")
    sig_t = qmi_req(s, nas_addr, 4, 0x004F)
    for t_id in (0x14, 0x13, 0x12):
      if t_id in sig_t and len(sig_t[t_id]) >= 1:
        val = struct.unpack("<b", sig_t[t_id][:1])[0]
        rssi = str(val)
        break
    s.close()
  if sub >= 0 and dms_addr:
    sd = socket.socket(AF_QIPCRTR, socket.SOCK_DGRAM)
    qmi_req(sd, dms_addr, 1, 0x0054, struct.pack("<BHI", 0x01, 4, sub + 1))
    ms = qmi_req(sd, dms_addr, 2, 0x0024)
    if 0x01 in ms:
      raw_n = ms[0x01].decode("ascii", errors="ignore").strip("\x00 ")
      if raw_n:
        num = ("+" + raw_n) if not raw_n.startswith("+") else raw_n
    if 0x11 in ms:
      imsi = ms[0x11].decode("ascii", errors="ignore").strip("\x00 ")
    sd.close()
  op_clean = "".join(c for c in op if c not in "\r\n\"'$`")
  print(f"SLOT{slot}_REG_STATE={reg}")
  print(f"SLOT{slot}_RAT={rat}")
  print(f"SLOT{slot}_OPERATOR={op_clean}")
  print(f"SLOT{slot}_RSSI={rssi}")
  print(f"SLOT{slot}_NUMBER={num}")
  print(f"SLOT{slot}_IMSI={imsi}")
  if sub == 1:
    print(f"SEC_NAS_REG_STATE={reg}")
    print(f"SEC_NAS_RAT={rat}")
    print(f"SEC_NAS_OPERATOR={op_clean}")
    print(f"SEC_NAS_RSSI={rssi}")
PY
    fi
    exit 0
    ;;

  switch)
    target="${2:-1}"
    if [ "$target" != "1" ] && [ "$target" != "2" ]; then
      echo "Invalid slot: $target (must be 1 or 2)" >&2
      exit 1
    fi
    save_preferred_slot "$target"
    already_dsds=0
    if detect_qmicli_modem; then
      QMI_CARDS="$($QMICLI_MODEM --uim-get-card-status 2>/dev/null || true)"
      if [ -n "$QMI_CARDS" ]; then
        eval "$(parse_uim_card_status "$QMI_CARDS" "$target")"
        if [ "$SLOT1_STATE" = "present" ] && [ "$SLOT2_STATE" = "present" ] && \
           [ "$SLOT1_APP_STATE" = "ready" ] && [ "$SLOT2_APP_STATE" = "ready" ] && \
           [ "${PRIMARY_GW_SLOT:-0}" != "0" ] && [ "${SECONDARY_GW_SLOT:-0}" != "0" ]; then
          already_dsds=1
        fi
      fi
    fi
    if [ "$already_dsds" = "1" ] && [ "${3:-}" != "--swap-gw" ]; then
      ensure_dsds_nas_registration
      exit 0
    fi
    SIM_WAIT_TIME=2
    provision_slot "$target" 4
    killall -q bananarchy-dsds 2>/dev/null || true
    if [ "${3:-}" = "--swap-gw" ]; then
      spawn_enable_and_register "$target" 2
    else
      spawn_enable_and_register "$target" 0
    fi
    exit 0
    ;;

  verify-pin)
    slot="${2:-1}"
    pin="${3:-}"
    if [ -z "$pin" ]; then
      echo "Missing PIN" >&2
      exit 1
    fi
    prepare_slot_for_pin_op "$slot"
    eval "before_pin1=\${SLOT${slot}_PIN1_STATE:-}"
    eval "before_app=\${SLOT${slot}_APP_STATE:-}"
    eval "before_ret=\${SLOT${slot}_PIN1_RETRIES:-3}"
    verified=0
    wrong_pin=0
    if [ "$before_pin1" = "enabled-verified" ] || [ "$before_pin1" = "disabled" ] || [ "$before_app" = "ready" ]; then
      verified=1
    fi
    if [ "$verified" = "0" ] && [ "${PIN_OP_SESSION:-primary-gw-provisioning}" = "primary-gw-provisioning" ]; then
      sim_id="$(timeout 3 mmcli -m any 2>/dev/null | grep -oE 'SIM/[0-9]+' | head -n1 | cut -d'/' -f2 || true)"
      if [ -n "$sim_id" ]; then
        mm_pin_out="$(timeout 5 mmcli -i "$sim_id" --pin="$pin" 2>&1)" && verified=1 || {
          if printf "%s\n" "$mm_pin_out" | grep -qiE "IncorrectPin|SimPin|SimPuk|PinBlocked|incorrect"; then
            wrong_pin=1
          fi
        }
      fi
    fi
    if [ "$verified" = "0" ] && [ "$wrong_pin" = "0" ] && [ -n "$QMICLI_MODEM" ]; then
      qmi_pin_out="$($QMICLI_MODEM --uim-verify-pin="PIN1,$pin,session-type=${PIN_OP_SESSION:-primary-gw-provisioning}" 2>&1)" && verified=1 || {
        if printf "%s\n" "$qmi_pin_out" | grep -qiE "IncorrectPin|PinBlocked|Blocked"; then
          wrong_pin=1
        fi
      }
      if [ "$verified" = "0" ] && [ "$wrong_pin" = "0" ]; then
        qmi_pin_out="$($QMICLI_MODEM --uim-verify-pin="PIN1,$pin,session-type=card-slot-$slot" 2>&1)" && verified=1 || {
          if printf "%s\n" "$qmi_pin_out" | grep -qiE "IncorrectPin|PinBlocked|Blocked"; then
            wrong_pin=1
          fi
        }
      fi
    fi
    if [ "$verified" = "0" ] && [ -n "$QMICLI_MODEM" ]; then
      QMI_CARDS_AFTER="$($QMICLI_MODEM --uim-get-card-status 2>/dev/null || true)"
      if [ -n "$QMI_CARDS_AFTER" ]; then
        eval "$(parse_uim_card_status "$QMI_CARDS_AFTER" "$slot")"
        eval "after_pin1=\$SLOT${slot}_PIN1_STATE"
        eval "after_app=\$SLOT${slot}_APP_STATE"
        eval "after_ret=\$SLOT${slot}_PIN1_RETRIES"
        if [ "$after_pin1" = "enabled-verified" ] || [ "$after_pin1" = "disabled" ] || [ "$after_app" = "ready" ]; then
          verified=1
        elif [ "$after_ret" -lt "$before_ret" ] 2>/dev/null; then
          wrong_pin=1
        fi
      fi
    fi
    if [ "$verified" = "0" ] && [ "$wrong_pin" = "0" ]; then
      at_cpin="$("$0" at auto "AT+CPIN=\"$pin\"" 2>/dev/null || true)"
      if printf "%s\n" "$at_cpin" | grep -qE "(^|[[:space:]])OK([[:space:]]|$)"; then
        verified=1
      fi
    fi
    if [ "$verified" = "1" ]; then
      SIM_WAIT_TIME=2
      provision_slot "$PREFERRED_SIM_SLOT" 3 >/dev/null 2>&1 || true
      timeout 4 mmcli -m any -e >/dev/null 2>&1 || true
      spawn_enable_and_register "$PREFERRED_SIM_SLOT" 1
      exit 0
    fi
    exit 1
    ;;

  unblock-puk)
    slot="${2:-1}"
    puk="${3:-}"
    newpin="${4:-}"
    if [ -z "$puk" ] || [ -z "$newpin" ]; then
      echo "Missing PUK or new PIN" >&2
      exit 1
    fi
    prepare_slot_for_pin_op "$slot"
    unblocked=0
    if [ "${PIN_OP_SESSION:-primary-gw-provisioning}" = "primary-gw-provisioning" ]; then
      sim_id="$(timeout 3 mmcli -m any 2>/dev/null | grep -oE 'SIM/[0-9]+' | head -n1 | cut -d'/' -f2 || true)"
      if [ -n "$sim_id" ] && timeout 4 mmcli -i "$sim_id" --puk="$puk" --pin="$newpin" >/dev/null 2>&1; then
        unblocked=1
      fi
    fi
    if [ "$unblocked" = "0" ] && [ -n "$QMICLI_MODEM" ]; then
      if $QMICLI_MODEM --uim-unblock-pin="PIN1,$puk,$newpin,session-type=${PIN_OP_SESSION:-primary-gw-provisioning}" >/dev/null 2>&1; then
        unblocked=1
      elif $QMICLI_MODEM --uim-unblock-pin="PIN1,$puk,$newpin,session-type=card-slot-$slot" >/dev/null 2>&1; then
        unblocked=1
      elif $QMICLI_MODEM --uim-unblock-pin="PIN1,$puk,$newpin" >/dev/null 2>&1; then
        unblocked=1
      elif $QMICLI_MODEM --dms-uim-unblock-pin="PIN,$puk,$newpin" >/dev/null 2>&1; then
        unblocked=1
      fi
    fi
    if [ "$unblocked" = "0" ]; then
      at_cpin="$("$0" at auto "AT+CPIN=\"$puk\",\"$newpin\"" 2>/dev/null || true)"
      if printf "%s\n" "$at_cpin" | grep -qE "(^|[[:space:]])OK([[:space:]]|$)"; then
        unblocked=1
      fi
    fi
    if [ "$unblocked" = "1" ]; then
      SIM_WAIT_TIME=2
      provision_slot "$PREFERRED_SIM_SLOT" 3 >/dev/null 2>&1 || true
      timeout 4 mmcli -m any -e >/dev/null 2>&1 || true
      spawn_enable_and_register "$PREFERRED_SIM_SLOT" 1
      exit 0
    fi
    exit 1
    ;;

  set-pin-lock)
    slot="${2:-1}"
    mode="${3:-enable}"
    pin="${4:-}"
    if [ -z "$pin" ] || { [ "$mode" != "enable" ] && [ "$mode" != "disable" ]; }; then
      echo "Usage: $0 set-pin-lock <1|2> <enable|disable> <pin>" >&2
      exit 1
    fi
    prepare_slot_for_pin_op "$slot"
    if [ -n "$QMICLI_MODEM" ]; then
      if $QMICLI_MODEM --uim-set-pin-protection="PIN1,$mode,$pin,session-type=${PIN_OP_SESSION:-primary-gw-provisioning}" >/dev/null 2>&1; then
        exit 0
      fi
      if $QMICLI_MODEM --uim-set-pin-protection="PIN1,$mode,$pin,session-type=card-slot-$slot" >/dev/null 2>&1; then
        exit 0
      fi
      if $QMICLI_MODEM --dms-uim-set-pin-protection="PIN,$mode,$pin" >/dev/null 2>&1; then
        exit 0
      fi
    fi
    if [ "${PIN_OP_SESSION:-primary-gw-provisioning}" = "primary-gw-provisioning" ]; then
      sim_id="$(mmcli -m any 2>/dev/null | grep -oE 'SIM/[0-9]+' | head -n1 | cut -d'/' -f2 || true)"
      if [ -n "$sim_id" ]; then
        if [ "$mode" = "enable" ] && mmcli -i "$sim_id" --enable-pin --pin="$pin" >/dev/null 2>&1; then
          exit 0
        elif [ "$mode" = "disable" ] && mmcli -i "$sim_id" --disable-pin --pin="$pin" >/dev/null 2>&1; then
          exit 0
        fi
      fi
    fi
    exit 1
    ;;

  change-pin)
    slot="${2:-1}"
    oldpin="${3:-}"
    newpin="${4:-}"
    if [ -z "$oldpin" ] || [ -z "$newpin" ]; then
      echo "Usage: $0 change-pin <1|2> <oldpin> <newpin>" >&2
      exit 1
    fi
    prepare_slot_for_pin_op "$slot"
    if [ -n "$QMICLI_MODEM" ]; then
      if $QMICLI_MODEM --uim-change-pin="PIN1,$oldpin,$newpin,session-type=${PIN_OP_SESSION:-primary-gw-provisioning}" >/dev/null 2>&1; then
        exit 0
      fi
      if $QMICLI_MODEM --uim-change-pin="PIN1,$oldpin,$newpin,session-type=card-slot-$slot" >/dev/null 2>&1; then
        exit 0
      fi
      if $QMICLI_MODEM --dms-uim-change-pin="PIN,$oldpin,$newpin" >/dev/null 2>&1; then
        exit 0
      fi
    fi
    if [ "${PIN_OP_SESSION:-primary-gw-provisioning}" = "primary-gw-provisioning" ]; then
      sim_id="$(mmcli -m any 2>/dev/null | grep -oE 'SIM/[0-9]+' | head -n1 | cut -d'/' -f2 || true)"
      if [ -n "$sim_id" ] && mmcli -i "$sim_id" --change-pin="$newpin" --pin="$oldpin" >/dev/null 2>&1; then
        exit 0
      fi
    fi
    exit 1
    ;;

  imei)
    if [ -f /tmp/bananarchy_duress_mode ] && [ -s /tmp/bananarchy_duress_imei ]; then
      cat /tmp/bananarchy_duress_imei
      exit 0
    fi
    imei1=""
    imei2=""
    imei_sv=""
    if [ -s /tmp/bananarchy_imei_override ]; then
      # shellcheck disable=SC1091
      . /tmp/bananarchy_imei_override 2>/dev/null || true
      imei1="${IMEI1:-}"
      imei2="${IMEI2:-}"
    elif [ -s /var/lib/bananarchy/imei_override ]; then
      # shellcheck disable=SC1091
      . /var/lib/bananarchy/imei_override 2>/dev/null || true
      imei1="${IMEI1:-}"
      imei2="${IMEI2:-}"
    fi
    if detect_qmicli_modem; then
      dms_ids="$($QMICLI_MODEM --dms-get-ids 2>/dev/null || true)"
      [ -z "$imei1" ] && imei1="$(printf "%s\n" "$dms_ids" | sed -n "s/.*IMEI: '\([0-9]\{14,16\}\)'/\1/p" | head -n1)"
      imei_sv="$(printf "%s\n" "$dms_ids" | sed -n "s/.*IMEI SV: '\([^']*\)'/\1/p" | head -n1)"
    fi
    if [ -z "$imei1" ]; then
      imei1="$(mmcli -m any -K 2>/dev/null | awk -F': ' '/modem\.3gpp\.imei/ {print $2; exit}')"
    fi
    # Decode NV 550 (SIM1) and context1/550 (SIM2) from tunning tar partition if present
    if { [ -z "$imei1" ] || [ -z "$imei2" ]; } && [ -e /dev/disk/by-partlabel/tunning ] && command -v python3 >/dev/null 2>&1; then
      eval "$(python3 - /dev/disk/by-partlabel/tunning << 'PY' 2>/dev/null || true
import sys, tarfile
def dec(d):
  if not d or len(d) < 9 or d[0] != 0x08 or (d[1] & 0x0F) != 0x0A: return ""
  s = str((d[1] >> 4) & 0x0F) + "".join(f"{b & 0x0F}{(b >> 4) & 0x0F}" for b in d[2:9])
  return s if s.isdigit() and len(s) == 15 else ""
try:
  with tarfile.open(sys.argv[1], "r:*") as tf:
    for m in tf.getmembers():
      n = m.name.lstrip("./")
      if n == "nvm/num/550":
        v = dec(tf.extractfile(m).read())
        if v: print(f"TUN1={v}")
      elif n == "nvm/context1/550":
        v = dec(tf.extractfile(m).read())
        if v: print(f"TUN2={v}")
except Exception:
  pass
PY
)"
      [ -z "$imei1" ] && [ -n "${TUN1:-}" ] && imei1="$TUN1"
      [ -z "$imei2" ] && [ -n "${TUN2:-}" ] && imei2="$TUN2"
    fi
    # Decode IMEI1 (0x88) and IMEI2 (0x108) from rf_nv partition (nokia-sparkler, nokia-leo, etc.)
    if { [ -z "$imei1" ] || [ -z "$imei2" ]; } && { [ -e /dev/disk/by-partlabel/rf_nv ] || [ -e /dev/disk/by-partlabel/rfnv ]; } && command -v python3 >/dev/null 2>&1; then
      rfnv_dev="/dev/disk/by-partlabel/rf_nv"
      [ -e "$rfnv_dev" ] || rfnv_dev="/dev/disk/by-partlabel/rfnv"
      eval "$(python3 - "$rfnv_dev" << 'PY' 2>/dev/null || true
import sys
SIGVAL = b"IEMI"
SIGPOS = 0x80
SIGVAL2 = b"\x92\x8a\x9a\x92"
SIGPOS2 = SIGPOS + 0x80
def dec(d):
  if not d or len(d) < 9: return ""
  inv = bytes(((b >> 4) | ((b & 15) << 4)) for b in d[:9])
  s = inv.hex()[3:]
  return s if len(s) == 15 and s.isdigit() else ""
try:
  with open(sys.argv[1], "rb") as fh:
    fh.seek(SIGPOS)
    v1 = fh.read(4)
    fh.seek(SIGPOS2)
    v2 = fh.read(4)
    if v1 == SIGVAL and v2 == SIGVAL2:
      fh.seek(SIGPOS + 8)
      i1 = dec(fh.read(9))
      fh.seek(SIGPOS2 + 8)
      i2 = dec(fh.read(9))
      if i1: print(f"RFNV1={i1}")
      if i2: print(f"RFNV2={i2}")
except Exception:
  pass
PY
)"
      [ -z "$imei1" ] && [ -n "${RFNV1:-}" ] && imei1="$RFNV1"
      [ -z "$imei2" ] && [ -n "${RFNV2:-}" ] && imei2="$RFNV2"
    fi
    # Query secondary AT channel (/dev/wwan0at1) if present
    if [ -c "/dev/wwan0at1" ]; then
      at_out="$(timeout 1 sh -c '
        stty -F /dev/wwan0at1 raw -echo 115200 2>/dev/null || true
        (cat /dev/wwan0at1 & pid=$!; printf "AT+CGSN\r\n" > /dev/wwan0at1; sleep 0.25; kill $pid 2>/dev/null) 2>/dev/null
      ' 2>/dev/null | tr -d "\r" | grep -oE '^[0-9]{15}$' | head -n1 || true)"
      if [ -n "$at_out" ] && [ "$at_out" != "$imei1" ]; then
        imei2="$at_out"
      fi
    fi
    # Scan factory partitions for Luhn-valid 15-digit IMEIs (TAC 35...)
    if [ -z "$imei2" ]; then
      for part in /dev/disk/by-partlabel/traceability /dev/disk/by-partlabel/tunning /dev/disk/by-partlabel/devinfo /dev/disk/by-partlabel/oem; do
        [ -e "$part" ] || continue
        cand_list="$(strings -n 14 "$part" 2>/dev/null | grep -oE '35[0-9]{13}' | awk '
          {
            val = $0
            sum = 0
            for (i = 1; i <= 14; i++) {
              d = substr(val, i, 1) + 0
              if (i % 2 == 0) {
                d *= 2
                if (d > 9) d -= 9
              }
              sum += d
            }
            chk = (10 - (sum % 10)) % 10
            if (chk == (substr(val, 15, 1) + 0)) print val
          }
        ' || true)"
        for c in $cand_list; do
          if [ -z "$imei1" ]; then
            imei1="$c"
          elif [ "$c" != "$imei1" ] && [ -z "$imei2" ]; then
            imei2="$c"
            break 2
          fi
        done
      done
    fi
    echo "IMEI1=${imei1}"
    echo "IMEI2=${imei2}"
    echo "IMEI_SV=${imei_sv}"
    ;;

  usb-tether)
    mode="${2:-status}"
    case "$mode" in
      on)
        ensure_usb_network_gadget
        sysctl -w net.ipv4.ip_forward=1 >/dev/null 2>&1 || true
        sysctl -w net.ipv4.conf.usb0.route_localnet=1 >/dev/null 2>&1 || true
        nft add table ip nat 2>/dev/null || true
        nft 'add chain ip nat prerouting { type nat hook prerouting priority -100 ; }' 2>/dev/null || true
        nft 'add chain ip nat postrouting { type nat hook postrouting priority 100 ; }' 2>/dev/null || true
        nft flush chain ip nat prerouting 2>/dev/null || true
        nft add rule ip nat prerouting iifname "usb*" udp dport 53 dnat to 127.0.0.1:53 2>/dev/null || true
        nft add rule ip nat prerouting iifname "usb*" tcp dport 53 dnat to 127.0.0.1:53 2>/dev/null || true
        nft add rule ip nat postrouting oifname "wwan*" masquerade 2>/dev/null || true
        nft add rule ip nat postrouting oifname "wlan*" masquerade 2>/dev/null || true
        ip addr show dev usb0 2>/dev/null | grep -q "172.16.42.1" || ip addr add 172.16.42.1/16 dev usb0 2>/dev/null || true
        ip link set usb0 up 2>/dev/null || true
        echo "1" > /tmp/bananarchy_usb_tether.active
        ;;
      off)
        ensure_usb_network_gadget
        sysctl -w net.ipv4.conf.usb0.route_localnet=0 >/dev/null 2>&1 || true
        sysctl -w net.ipv4.ip_forward=0 >/dev/null 2>&1 || true
        nft delete table ip nat 2>/dev/null || true
        nmcli connection delete USBNetworkShare >/dev/null 2>&1 || true
        ip addr show dev usb0 2>/dev/null | grep -q "172.16.42.1" || ip addr add 172.16.42.1/16 dev usb0 2>/dev/null || true
        ip link set usb0 up 2>/dev/null || true
        rm -f /tmp/bananarchy_usb_tether.active
        ;;
      *)
        if [ -f /tmp/bananarchy_usb_tether.active ] && [ "$(sysctl -n net.ipv4.ip_forward 2>/dev/null || echo 0)" = "1" ]; then
          echo "ACTIVE=1"
        else
          echo "ACTIVE=0"
        fi
        ;;
    esac
    ;;

  at)
    port="${2:-auto}"
    shift 2 2>/dev/null || true
    at_cmd="$*"
    if [ -z "$at_cmd" ]; then
      echo "ERROR: Empty AT command"
      exit 1
    fi
    run_at_dev() {
      timeout 3 sh -c '
        dev="$1"
        cmd="$2"
        tmpf="/tmp/at_resp_$$.txt"
        rpid=""
        trap '\''[ -n "$rpid" ] && kill "$rpid" 2>/dev/null || true; rm -f "$tmpf"'\'' EXIT INT TERM
        rm -f "$tmpf"
        cat "$dev" > "$tmpf" 2>/dev/null &
        rpid=$!
        sleep 0.04
        printf "%s\r\n" "$cmd" > "$dev" 2>/dev/null || true
        i=0
        while [ "$i" -lt 16 ]; do
          if grep -qE "(^|[[:space:]])(OK|ERROR|\+CME ERROR|\+CMS ERROR)([[:space:]]|$)" "$tmpf" 2>/dev/null; then
            break
          fi
          sleep 0.08
          i=$((i + 1))
        done
        kill "$rpid" 2>/dev/null || true
        wait "$rpid" 2>/dev/null || true
        rpid=""
        tr -d "\r" < "$tmpf" 2>/dev/null || true
        rm -f "$tmpf"
      ' _ "$1" "$2" 2>/dev/null | sed '/^[[:space:]]*$/d' || true
    }
    if [ "$port" = "all" ]; then
      got_any=0
      for dev in /dev/wwan0at*; do
        [ -c "$dev" ] || continue
        resp="$(run_at_dev "$dev" "$at_cmd")"
        if [ -n "$resp" ]; then
          got_any=1
          printf '[%s]\n%s\n' "${dev#/dev/}" "$resp"
        fi
      done
      if [ "$got_any" -eq 1 ]; then
        exit 0
      fi
      echo "ERROR: No response from modem AT channel"
      exit 1
    fi
    resp=""
    if [ "$PREFERRED_SIM_SLOT" = "2" ]; then
      at_candidates="$port /dev/wwan0at1 /dev/wwan0at0"
    else
      at_candidates="$port /dev/wwan0at0 /dev/wwan0at1"
    fi
    for candidate in $at_candidates; do
      case "$candidate" in
        wwan0at[0-9]*)
          dev="/dev/$candidate"
          ;;
        /dev/wwan0at[0-9]*)
          dev="$candidate"
          ;;
        *)
          dev=""
          ;;
      esac
      if [ -n "$dev" ] && [ -c "$dev" ]; then
        resp="$(run_at_dev "$dev" "$at_cmd")"
        if [ -n "$resp" ]; then
          printf "%s\n" "$resp"
          exit 0
        fi
      fi
      if [ "$port" != "auto" ] && [ "$candidate" = "$port" ]; then
        break
      fi
    done
    if [ "$port" = "auto" ]; then
      mm_out="$(mmcli -m any --command="$at_cmd" 2>/dev/null || true)"
      if [ -n "$mm_out" ]; then
        printf "%s\n" "$mm_out" | sed "s/^response: '\(.*\)'$/\1/"
        exit 0
      fi
    fi
    echo "ERROR: No response from modem AT channel"
    exit 1
    ;;

  ussd)
    ussd_mode="${2:-initiate}"
    shift 2 2>/dev/null || true
    req_sim="$PREFERRED_SIM_SLOT"
    if [ "${1:-}" = "--sim" ] && [ -n "${2:-}" ]; then
      req_sim="$2"
      shift 2 2>/dev/null || true
    elif [ -n "${SXMO_SIM_SLOT:-}" ]; then
      req_sim="$SXMO_SIM_SLOT"
    fi
    ussd_code="$*"
    if [ "$ussd_mode" = "cancel" ]; then
      rm -f /tmp/sxmo_ussd_session_state
      if command -v python3 >/dev/null 2>&1; then
        python3 - << 'PY' 2>/dev/null || true
import socket, struct, select
AF_QIPCRTR = 42
ls = socket.socket(AF_QIPCRTR, socket.SOCK_DGRAM)
node, _ = ls.getsockname()
ls.sendto(struct.pack("<IIIII", 10, 9, 0, 0, 0), (node, 0xfffffffe))
v_addr = None
while True:
  r, _, _ = select.select([ls], [], [], 0.12)
  if not r: break
  d, _ = ls.recvfrom(256)
  if len(d) >= 20:
    cmd, srv, inst, n, p = struct.unpack("<IIIII", d[:20])
    if cmd == 4 and srv == 9 and p != 0: v_addr = (n, p)
    if cmd == 4 and srv == 0 and n == 0 and p == 0: break
ls.close()
if v_addr:
  for sub in (0, 1):
    s = socket.socket(AF_QIPCRTR, socket.SOCK_DGRAM)
    s.sendto(struct.pack("<BHHH", 0, 1, 0x0044, 4) + struct.pack("<BHB", 1, 1, sub), v_addr)
    select.select([s], [], [], 0.1)
    s.sendto(struct.pack("<BHHH", 0, 2, 0x003C, 0), v_addr)
    select.select([s], [], [], 0.1)
    s.close()
PY
      fi
      mmcli -m any --3gpp-ussd-cancel >/dev/null 2>&1 || true
      "$0" at auto 'AT+CUSD=2' >/dev/null 2>&1 || true
      echo "USSD session cancelled."
      exit 0
    fi
    if [ -z "$ussd_code" ]; then
      echo "ERROR: Empty USSD code"
      exit 1
    fi
    prim_slot="$PREFERRED_SIM_SLOT"
    sec_slot="0"
    if detect_qmicli_modem; then
      QMI_CARDS="$($QMICLI_MODEM --uim-get-card-status 2>/dev/null || true)"
      if [ -n "$QMI_CARDS" ]; then
        eval "$(parse_uim_card_status "$QMI_CARDS" "$PREFERRED_SIM_SLOT")"
        prim_slot="${PRIMARY_GW_SLOT:-$PREFERRED_SIM_SLOT}"
        sec_slot="${SECONDARY_GW_SLOT:-0}"
      fi
    fi
    run_qmi_voice_ussd() {
      command -v python3 >/dev/null 2>&1 || return 1
      python3 - "$1" "$2" "$3" << 'PY' 2>/dev/null
import os, socket, struct, select, sys, time

mode = sys.argv[1]
code = sys.argv[2]
sub = int(sys.argv[3]) if len(sys.argv) > 3 and sys.argv[3].isdigit() else 0
AF_QIPCRTR = 42
QRTR_PORT_CTRL = 0xfffffffe
QRTR_TYPE_NEW_SERVER = 4
QRTR_TYPE_NEW_LOOKUP = 10
QMI_SERVICE_VOICE = 9

ls = socket.socket(AF_QIPCRTR, socket.SOCK_DGRAM)
node, _ = ls.getsockname()
ls.sendto(struct.pack("<IIIII", QRTR_TYPE_NEW_LOOKUP, QMI_SERVICE_VOICE, 0, 0, 0), (node, QRTR_PORT_CTRL))
v_addr = None
while True:
  r, _, _ = select.select([ls], [], [], 0.15)
  if not r:
    break
  data, _ = ls.recvfrom(256)
  if len(data) >= 20:
    cmd, srv, inst, srv_node, srv_port = struct.unpack("<IIIII", data[:20])
    if cmd == QRTR_TYPE_NEW_SERVER:
      if srv == QMI_SERVICE_VOICE and srv_port != 0:
        v_addr = (srv_node, srv_port)
      if srv == 0 and srv_node == 0 and srv_port == 0:
        break
ls.close()
if not v_addr:
  sys.exit(1)

s = socket.socket(AF_QIPCRTR, socket.SOCK_DGRAM)
s.sendto(struct.pack("<BHHH", 0x00, 1, 0x0044, 4) + struct.pack("<BHB", 0x01, 1, sub), v_addr)
select.select([s], [], [], 0.2)
try:
  s.recvfrom(512)
except Exception:
  pass

# Register for USSD indications (0x0003, TLV 0x16 = 1)
ind_tlv = struct.pack("<BHB", 0x16, 1, 1)
s.sendto(struct.pack("<BHHH", 0x00, 2, 0x0003, len(ind_tlv)) + ind_tlv, v_addr)
select.select([s], [], [], 0.2)
try:
  s.recvfrom(512)
except Exception:
  pass

if mode != "respond":
  s.sendto(struct.pack("<BHHH", 0x00, 3, 0x003C, 0), v_addr)
  select.select([s], [], [], 0.15)
  try:
    s.recvfrom(512)
  except Exception:
    pass

cb = code.encode("ascii", errors="ignore")
uss_data = struct.pack("<BB", 0x01, len(cb)) + cb
tlv = struct.pack("<BH", 0x01, len(uss_data)) + uss_data
msg_id = 0x003B if mode == "respond" else 0x003A
s.sendto(struct.pack("<BHHH", 0x00, 4, msg_id, len(tlv)) + tlv, v_addr)

def decode_uss_bytes(val):
  if len(val) < 3:
    return ""
  dcs = val[0]
  ulen = val[1]
  raw = val[2:2+ulen]
  if dcs in (2, 0x48) or (len(raw) >= 2 and raw[0] == 0x04):
    return raw.decode("utf-16-be", errors="ignore").strip()
  return raw.decode("utf-8", errors="ignore").strip()

def decode_utf16le_tlv(val):
  if len(val) < 3:
    return ""
  nchars = val[0]
  raw = val[1:1 + nchars * 2]
  return raw.decode("utf-16-le", errors="ignore").strip()

def write_session_state(active):
  try:
    with open("/tmp/sxmo_ussd_session_state", "w") as f:
      f.write("user-response\n" if active else "idle\n")
  except Exception:
    pass

deadline = time.time() + 14.0
while time.time() < deadline:
  r, _, _ = select.select([s], [], [], 0.5)
  if not r:
    continue
  pkt, _ = s.recvfrom(2048)
  if len(pkt) < 7:
    continue
  flags, txn, mid, _ = struct.unpack("<BHHH", pkt[:7])
  tlvs = {}
  pos = 7
  while pos + 3 <= len(pkt):
    tt, tl = struct.unpack("<BH", pkt[pos:pos+3])
    pos += 3
    tlvs[tt] = pkt[pos:pos+tl]
    pos += tl

  if mid == 0x003E:
    user_action = tlvs.get(0x01, b"\x01")[0] if 0x01 in tlvs and len(tlvs[0x01]) >= 1 else 1
    txt = ""
    if 0x11 in tlvs:
      txt = decode_utf16le_tlv(tlvs[0x11])
    if not txt and 0x10 in tlvs:
      txt = decode_uss_bytes(tlvs[0x10])
    if txt:
      write_session_state(user_action == 2)
      print(txt)
      s.close()
      sys.exit(0)
  elif mid in (0x003A, 0x003B):
    if 0x02 in tlvs and len(tlvs[0x02]) >= 4:
      res, err = struct.unpack("<HH", tlvs[0x02][:4])
      if res != 0:
        write_session_state(False)
        break
    txt = ""
    if 0x16 in tlvs:
      txt = decode_utf16le_tlv(tlvs[0x16])
    if not txt and 0x12 in tlvs:
      txt = decode_uss_bytes(tlvs[0x12])
    if not txt and 0x11 in tlvs:
      txt = decode_uss_bytes(tlvs[0x11])
    if txt:
      write_session_state(False)
      print(txt)
      s.close()
      sys.exit(0)
  elif mid == 0x003D:
    write_session_state(False)
s.close()
sys.exit(1)
PY
    }
    # If requested SIM is Secondary GW, use QMI VOICE USSD on sub=1
    if [ "$req_sim" = "$sec_slot" ] && [ "$sec_slot" != "0" ]; then
      qmi_ussd="$(run_qmi_voice_ussd "$ussd_mode" "$ussd_code" "1" || true)"
      if [ -n "$qmi_ussd" ]; then
        printf "%s\n" "$qmi_ussd"
        exit 0
      fi
    fi
    mm_out=""
    if [ "$req_sim" = "$prim_slot" ]; then
      qmi_sess=""
      [ -r /tmp/sxmo_ussd_session_state ] && { read -r qmi_sess < /tmp/sxmo_ussd_session_state 2>/dev/null || qmi_sess=""; }
      mm_modem=""
      if [ "$ussd_mode" != "respond" ] || [ "$qmi_sess" != "user-response" ]; then
        mm_modem="$(mmcli -L 2>/dev/null | awk '{for (i=1; i<=NF; i++) if ($i ~ /^\/org\/freedesktop\/ModemManager1\/Modem\/[0-9]+$/) {print $i; exit}}')"
      fi
      if [ -n "$mm_modem" ]; then
        rm -f /tmp/sxmo_ussd_session_state
        mm_state="$(mmcli -m "$mm_modem" -K 2>/dev/null | awk -F':[[:space:]]*' '{gsub(/[[:space:]]+$/, "", $1); if ($1 == "modem.generic.state") {print $2; exit}}' || true)"
        if [ "$mm_state" = "disabled" ] || [ -z "$mm_state" ]; then
          mmcli -m "$mm_modem" -e >/dev/null 2>&1 || true
          sleep 1
        fi
        modem_dbus_path="$mm_modem"
        get_ussd_prop() {
          prop_name="$1"
          if [ -n "$modem_dbus_path" ] && command -v busctl >/dev/null 2>&1 && command -v jq >/dev/null 2>&1; then
            busctl -j get-property org.freedesktop.ModemManager1 "$modem_dbus_path" \
              org.freedesktop.ModemManager1.Modem.Modem3gpp.Ussd "$prop_name" 2>/dev/null | \
              jq -r '.data // empty' 2>/dev/null || true
          fi
        }
        get_ussd_state() {
          mmcli -m "$mm_modem" --3gpp-ussd-status -K 2>/dev/null | \
            awk -F':[[:space:]]*' '{gsub(/[[:space:]]+$/, "", $1); if ($1 == "modem.3gpp.ussd.status" || $1 == "modem.3gpp.ussd.state") {print $2; exit}}' || true
        }
        prev_notif="$(get_ussd_prop NetworkNotification)"
        prev_req="$(get_ussd_prop NetworkRequest)"
        ussd_st="$(get_ussd_state)"
        if [ "$ussd_mode" = "respond" ] && [ "$ussd_st" != "user-response" ]; then
          case "$ussd_code" in
            \**\#|\#*\#)
              ussd_mode="initiate"
              ;;
          esac
        fi
        ev_file="/tmp/ussd_dbus_$$.log"
        rm -f "$ev_file"
        if command -v dbus-monitor >/dev/null 2>&1; then
          dbus-monitor --system "interface='org.freedesktop.DBus.Properties',member='PropertiesChanged',arg0='org.freedesktop.ModemManager1.Modem.Modem3gpp.Ussd'" >"$ev_file" 2>/dev/null &
          ev_pid=$!
        else
          ev_pid=""
        fi
        cleanup_ev() {
          if [ -n "${ev_pid:-}" ]; then
            kill "$ev_pid" 2>/dev/null || true
            wait "$ev_pid" 2>/dev/null || true
          fi
          rm -f "$ev_file"
        }
        mm_rc=0
        if [ "$ussd_mode" = "respond" ]; then
          mm_out="$(mmcli --timeout=30 -m "$mm_modem" --3gpp-ussd-respond="$ussd_code" 2>&1)" || mm_rc=$?
        else
          if [ "$ussd_st" = "active" ] || [ "$ussd_st" = "user-response" ]; then
            mmcli -m "$mm_modem" --3gpp-ussd-cancel >/dev/null 2>&1 || true
          fi
          mm_out="$(mmcli --timeout=30 -m "$mm_modem" --3gpp-ussd-initiate="$ussd_code" 2>&1)" || mm_rc=$?
        fi
        if [ "$mm_rc" -eq 0 ] && [ -n "$mm_out" ]; then
          reply="$(printf "%s\n" "$mm_out" | sed \
            -e "1s/^USSD session initiated; new reply from network: '//" \
            -e "1s/^response successfully sent in USSD session; new reply from network: '//" \
            -e "1s/^USSD response sent; new reply from network: '//" \
            -e "\$s/'$//")"
          if [ -n "$reply" ]; then
            cleanup_ev
            printf "%s\n" "$reply"
            exit 0
          fi
        fi
        # Check if the USSD response arrived asynchronously via D-Bus properties
        w=0
        while [ "$w" -lt 15 ]; do
          cur_req="$(get_ussd_prop NetworkRequest)"
          cur_notif="$(get_ussd_prop NetworkNotification)"
          cur_st="$(get_ussd_state)"
          if [ -n "$cur_req" ] && { [ "$cur_req" != "$prev_req" ] || [ "$cur_st" = "user-response" ] || grep -q "NetworkRequest" "$ev_file" 2>/dev/null; }; then
            cleanup_ev
            printf "%s\n" "$cur_req"
            exit 0
          fi
          if [ -n "$cur_notif" ] && { [ "$cur_notif" != "$prev_notif" ] || grep -q "NetworkNotification" "$ev_file" 2>/dev/null || printf "%s" "$mm_out" | grep -q "USSD terminated by network"; }; then
            cleanup_ev
            printf "%s\n" "$cur_notif"
            exit 0
          fi
          if [ "$cur_st" != "active" ] && [ "$w" -ge 3 ]; then
            if [ -n "$cur_req" ]; then
              cleanup_ev
              printf "%s\n" "$cur_req"
              exit 0
            fi
            if [ -n "$cur_notif" ]; then
              cleanup_ev
              printf "%s\n" "$cur_notif"
              exit 0
            fi
            break
          fi
          sleep 0.2
          w=$((w + 1))
        done
        cleanup_ev
      fi
      # Fallback to direct QMI VOICE USSD on sub=0 when ModemManager is unavailable or fails
      qmi_ussd="$(run_qmi_voice_ussd "$ussd_mode" "$ussd_code" "0" || true)"
      if [ -n "$qmi_ussd" ]; then
        printf "%s\n" "$qmi_ussd"
        exit 0
      fi
    else
      fallback_sub="0"
      [ "$req_sim" = "2" ] && fallback_sub="1"
      qmi_ussd="$(run_qmi_voice_ussd "$ussd_mode" "$ussd_code" "$fallback_sub" || true)"
      if [ -n "$qmi_ussd" ]; then
        printf "%s\n" "$qmi_ussd"
        exit 0
      fi
    fi
    # Fallback to direct AT+CUSD on the requested SIM AT port
    if [ "$req_sim" = "$sec_slot" ] && [ "$sec_slot" != "0" ]; then
      at_candidates="/dev/wwan0at1 /dev/wwan0at0"
    elif [ "$req_sim" = "2" ]; then
      at_candidates="/dev/wwan0at1 /dev/wwan0at0"
    else
      at_candidates="/dev/wwan0at0 /dev/wwan0at1"
    fi
    for dev in $at_candidates; do
      [ -c "$dev" ] || continue
      cusd_out="$(timeout 12 sh -c '
        dev="$1"
        code="$2"
        tmpf="/tmp/ussd_resp_$$.txt"
        rm -f "$tmpf"
        cat "$dev" > "$tmpf" 2>/dev/null &
        rpid=$!
        sleep 0.05
        printf "AT+CSCS=\"GSM\";+CUSD=1,\"%s\",15\r\n" "$code" > "$dev" 2>/dev/null || true
        i=0
        while [ "$i" -lt 80 ]; do
          if grep -qE "\+CUSD:[[:space:]]*[0-9]+" "$tmpf" 2>/dev/null; then
            break
          fi
          if grep -qE "(^|[[:space:]])(\+CME ERROR|\+CMS ERROR|ERROR)([[:space:]]|$)" "$tmpf" 2>/dev/null; then
            break
          fi
          sleep 0.1
          i=$((i + 1))
        done
        kill "$rpid" 2>/dev/null || true
        wait "$rpid" 2>/dev/null || true
        tr -d "\r" < "$tmpf" 2>/dev/null || true
        rm -f "$tmpf"
      ' _ "$dev" "$ussd_code" 2>/dev/null || true)"
      cusd_msg="$(printf "%s\n" "$cusd_out" | sed -n 's/.*+CUSD:[[:space:]]*[0-9]*,[[:space:]]*"\([^"]*\)".*/\1/p' | tail -n1)"
      if [ -n "$cusd_msg" ]; then
        printf "%s\n" "$cusd_msg"
        exit 0
      fi
    done
    case "${mm_out:-}" in
      ""|*"couldn't find modem"*)
        echo "ERROR: USSD request failed"
        ;;
      *)
        printf "%s\n" "$mm_out"
        ;;
    esac
    exit 1
    ;;

  sms-send)
    req_slot="${2:-$PREFERRED_SIM_SLOT}"
    dest_num="${3:-}"
    msg_src="${4:-}"
    if [ -z "$dest_num" ] || [ -z "$msg_src" ]; then
      echo "Usage: $0 sms-send <1|2> <number> <text_file_or_text>" >&2
      exit 1
    fi
    prim_slot="$PREFERRED_SIM_SLOT"
    sec_slot="0"
    if detect_qmicli_modem; then
      QMI_CARDS="$($QMICLI_MODEM --uim-get-card-status 2>/dev/null || true)"
      if [ -n "$QMI_CARDS" ]; then
        eval "$(parse_uim_card_status "$QMI_CARDS" "$PREFERRED_SIM_SLOT")"
        prim_slot="${PRIMARY_GW_SLOT:-$PREFERRED_SIM_SLOT}"
        sec_slot="${SECONDARY_GW_SLOT:-0}"
      fi
    fi
    target_sub=0
    if [ "$req_slot" = "$sec_slot" ] && [ "$sec_slot" != "0" ]; then
      target_sub=1
    fi
    python3 - "$target_sub" "$dest_num" "$msg_src" << 'PY'
import os, random, select, socket, struct, sys

sub = int(sys.argv[1]) if sys.argv[1].isdigit() else 0
dest = "".join(c for c in sys.argv[2] if c in "+0123456789")
src = sys.argv[3]
if os.path.isfile(src):
  with open(src, "r", encoding="utf-8", errors="replace") as f:
    text = f.read()
else:
  text = src
if text.endswith("\n"):
  text = text[:-1]

if not dest:
  print("ERROR: Invalid destination number", file=sys.stderr)
  sys.exit(1)

AF_QIPCRTR = 42
QRTR_PORT_CTRL = 0xfffffffe
QRTR_TYPE_NEW_SERVER = 4
QRTR_TYPE_NEW_LOOKUP = 10
QMI_SERVICE_WMS = 5

ls = socket.socket(AF_QIPCRTR, socket.SOCK_DGRAM)
node, _ = ls.getsockname()
ls.sendto(struct.pack("<IIIII", QRTR_TYPE_NEW_LOOKUP, QMI_SERVICE_WMS, 0, 0, 0), (node, QRTR_PORT_CTRL))
wms_addr = None
while True:
  r, _, _ = select.select([ls], [], [], 0.15)
  if not r:
    break
  data, _ = ls.recvfrom(256)
  if len(data) >= 20:
    cmd, srv, inst, srv_node, srv_port = struct.unpack("<IIIII", data[:20])
    if cmd == QRTR_TYPE_NEW_SERVER:
      if srv == QMI_SERVICE_WMS and srv_port != 0:
        wms_addr = (srv_node, srv_port)
      if srv == 0 and srv_node == 0 and srv_port == 0:
        break
ls.close()
if not wms_addr:
  print("ERROR: QMI WMS unavailable", file=sys.stderr)
  sys.exit(1)

def encode_da(number):
  ton_npi = 0x91 if number.startswith("+") else 0x81
  digits = [c for c in number if c.isdigit()]
  bcd = bytearray()
  for i in range(0, len(digits), 2):
    lo = int(digits[i])
    hi = int(digits[i + 1]) if (i + 1) < len(digits) else 0x0F
    bcd.append((hi << 4) | lo)
  return bytes([len(digits), ton_npi]) + bytes(bcd)

GSM7_BASIC = (
  "@\u00a3$\u00a5\u00e8\u00e9\u00f9\u00ec\u00f2\u00c7\n\u00d8\u00f8\r\u00c5\u00e5"
  "\u0394_\u03a6\u0393\u039b\u03a9\u03a0\u03a8\u03a3\u0398\u039e\x1b\u00c6\u00e6\u00df\u00c9"
  " !\"#\u00a4%&'()*+,-./0123456789:;<=>?"
  "\u00a1ABCDEFGHIJKLMNOPQRSTUVWXYZ\u00c4\u00d6\u00d1\u00dc\u00a7"
  "\u00bfabcdefghijklmnopqrstuvwxyz\u00e4\u00f6\u00f1\u00fc\u00e0"
)
GSM7_EXT_ENC = {
  "\f": 0x0A, "^": 0x14, "{": 0x28, "}": 0x29, "\\": 0x2F,
  "[": 0x3C, "~": 0x3D, "]": 0x3E, "|": 0x40, "\u20ac": 0x65
}
GSM7_BASIC_ENC = {ch: idx for idx, ch in enumerate(GSM7_BASIC) if ch != "\x1b"}

def encode_gsm7_septets(msg):
  septets = []
  for ch in msg:
    if ch in GSM7_BASIC_ENC:
      septets.append(GSM7_BASIC_ENC[ch])
    elif ch in GSM7_EXT_ENC:
      septets.append(0x1B)
      septets.append(GSM7_EXT_ENC[ch])
    else:
      return None
  return septets

def pack_gsm7(septets, udh=b""):
  if not udh:
    packed = bytearray()
    shift = 0
    cur = 0
    for s_val in septets:
      cur |= (s_val & 0x7F) << shift
      shift += 7
      while shift >= 8:
        packed.append(cur & 0xFF)
        cur >>= 8
        shift -= 8
    if shift > 0:
      packed.append(cur & 0xFF)
    return len(septets), bytes(packed)
  udh_bits = len(udh) * 8
  fill_bits = (7 - (udh_bits % 7)) % 7
  packed = bytearray()
  shift = fill_bits
  cur = 0
  for s_val in septets:
    cur |= (s_val & 0x7F) << shift
    shift += 7
    while shift >= 8:
      packed.append(cur & 0xFF)
      cur >>= 8
      shift -= 8
  if shift > 0:
    packed.append(cur & 0xFF)
  total_septets = ((udh_bits + fill_bits) // 7) + len(septets)
  return total_septets, bytes(udh) + bytes(packed)

def build_pdus(number, msg):
  da = encode_da(number)
  septets = encode_gsm7_septets(msg)
  if septets is not None:
    if len(septets) <= 160:
      udl, ud = pack_gsm7(septets)
      return [b"\x00\x01\x00" + da + b"\x00\x00" + bytes([udl]) + ud]
    chunks = []
    pos = 0
    while pos < len(septets):
      chunk = septets[pos:pos+153]
      if chunk and chunk[-1] == 0x1B and (pos + len(chunk)) < len(septets):
        chunk = chunk[:-1]
      chunks.append(chunk)
      pos += len(chunk)
    ref = random.randint(1, 254)
    total = len(chunks)
    pdus = []
    for idx, chunk in enumerate(chunks, 1):
      udh = bytes([0x05, 0x00, 0x03, ref, total, idx])
      udl, ud = pack_gsm7(chunk, udh)
      pdus.append(b"\x00\x41\x00" + da + b"\x00\x00" + bytes([udl]) + ud)
    return pdus

  u16 = msg.encode("utf-16-be")
  if len(u16) <= 140:
    return [b"\x00\x01\x00" + da + b"\x00\x08" + bytes([len(u16)]) + u16]

  chunks = [u16[i:i+134] for i in range(0, len(u16), 134)]
  ref = random.randint(1, 254)
  total = len(chunks)
  pdus = []
  for idx, chunk in enumerate(chunks, 1):
    udh = bytes([0x05, 0x00, 0x03, ref, total, idx])
    ud = udh + chunk
    # 0x41 = SMS-SUBMIT + UDHI
    pdus.append(b"\x00\x41\x00" + da + b"\x00\x08" + bytes([len(ud)]) + ud)
  return pdus

s = socket.socket(AF_QIPCRTR, socket.SOCK_DGRAM)
txn = 1
s.sendto(struct.pack("<BHHH", 0x00, txn, 0x004C, 4) + struct.pack("<BHB", 0x01, 1, sub), wms_addr)
txn += 1
select.select([s], [], [], 0.25)
try:
  s.recvfrom(512)
except Exception:
  pass

for pdu in build_pdus(dest, text):
  raw_val = struct.pack("<BH", 0x06, len(pdu)) + pdu
  tlv = struct.pack("<BH", 0x01, len(raw_val)) + raw_val
  s.sendto(struct.pack("<BHHH", 0x00, txn, 0x0020, len(tlv)) + tlv, wms_addr)
  my_txn = txn
  txn += 1
  ok = False
  while True:
    r, _, _ = select.select([s], [], [], 15.0)
    if not r:
      break
    resp, _ = s.recvfrom(1024)
    if len(resp) >= 7 and resp[0] == 0x02:
      r_txn, r_msg, _ = struct.unpack("<HHH", resp[1:7])
      if r_txn == my_txn and r_msg == 0x0020:
        pos = 7
        while pos + 3 <= len(resp):
          tt, tl = struct.unpack("<BH", resp[pos:pos+3])
          pos += 3
          if tt == 0x02 and tl >= 4:
            res, err = struct.unpack("<HH", resp[pos:pos+4])
            if res == 0 and err == 0:
              ok = True
          pos += tl
        break
  if not ok:
    s.close()
    print("ERROR: QMI WMS RawSend failed", file=sys.stderr)
    sys.exit(1)

s.close()
print("OK")
PY
    exit $?
    ;;

  slots)
    python3 - "$PREFERRED_SIM_SLOT" << 'PY'
import select, socket, struct, sys

pref_slot = int(sys.argv[1]) if len(sys.argv) > 1 and sys.argv[1].isdigit() else 1
prim_slot = pref_slot
sec_slot = 0
slot1_present = 0
slot2_present = 0

AF_QIPCRTR = 42
QRTR_PORT_CTRL = 0xfffffffe
QRTR_TYPE_NEW_SERVER = 4
QRTR_TYPE_NEW_LOOKUP = 10
QMI_SERVICE_UIM = 11

try:
  ls = socket.socket(AF_QIPCRTR, socket.SOCK_DGRAM)
  node, _ = ls.getsockname()
  ls.sendto(struct.pack("<IIIII", QRTR_TYPE_NEW_LOOKUP, QMI_SERVICE_UIM, 0, 0, 0), (node, QRTR_PORT_CTRL))
  u_addr = None
  while True:
    r, _, _ = select.select([ls], [], [], 0.08)
    if not r:
      break
    data, _ = ls.recvfrom(256)
    if len(data) >= 20:
      cmd, srv, inst, srv_node, srv_port = struct.unpack("<IIIII", data[:20])
      if cmd == QRTR_TYPE_NEW_SERVER:
        if srv == QMI_SERVICE_UIM and srv_port != 0:
          u_addr = (srv_node, srv_port)
        if srv == 0 and srv_node == 0 and srv_port == 0:
          break
  ls.close()
  if u_addr:
    us = socket.socket(AF_QIPCRTR, socket.SOCK_DGRAM)
    us.sendto(struct.pack("<BHHH", 0x00, 1, 0x002F, 0), u_addr)
    r, _, _ = select.select([us], [], [], 0.1)
    if r:
      resp, _ = us.recvfrom(2048)
      pos = 7
      while pos + 3 <= len(resp):
        tt, tl = struct.unpack("<BH", resp[pos:pos+3])
        pos += 3
        val = resp[pos:pos+tl]
        pos += tl
        if tt == 0x10 and len(val) >= 9:
          gw_pri, _, gw_sec, _ = struct.unpack("<HHHH", val[:8])
          if gw_pri != 0xFFFF:
            prim_slot = ((gw_pri >> 8) & 0xFF) + 1
          if gw_sec != 0xFFFF:
            sec_slot = ((gw_sec >> 8) & 0xFF) + 1
          num_slots = val[8]
          off = 9
          for s in range(min(num_slots, 2)):
            if off + 6 > len(val):
              break
            cstate = val[off]
            if s == 0 and cstate == 1:
              slot1_present = 1
            elif s == 1 and cstate == 1:
              slot2_present = 1
            num_apps = val[off + 5]
            off += 6
            for _ in range(num_apps):
              if off + 7 > len(val):
                break
              aid_len = val[off + 6]
              if off + 14 + aid_len > len(val):
                break
              off += 14 + aid_len
    us.close()
except Exception:
  pass

dual_active = 1 if (slot1_present and slot2_present and prim_slot in (1, 2) and sec_slot in (1, 2)) else 0
out = (
  f"PREFERRED_SLOT={pref_slot}\n"
  f"PRIMARY_GW_SLOT={prim_slot}\n"
  f"SECONDARY_GW_SLOT={sec_slot}\n"
  f"SLOT1_PRESENT={slot1_present}\n"
  f"SLOT2_PRESENT={slot2_present}\n"
  f"DUAL_SIM_ACTIVE={dual_active}\n"
)
sys.stdout.write(out)
try:
  with open("/tmp/sxmo_sim_slots", "w") as f:
    f.write(out)
except Exception:
  pass
PY
    exit 0
    ;;

  call-dial|call-accept|call-hangup|call-dtmf|call-list)
    sub_cmd="$cmd"
    arg1="${2:-}"
    arg2="${3:-}"
    prim_slot="$PREFERRED_SIM_SLOT"
    sec_slot="0"
    python3 - "$sub_cmd" "$arg1" "$arg2" "$prim_slot" "$sec_slot" << 'PY'
import os, select, socket, struct, sys, time

sub_cmd = sys.argv[1]
arg1 = sys.argv[2]
arg2 = sys.argv[3]
prim_slot = int(sys.argv[4]) if sys.argv[4].isdigit() else 1
sec_slot = int(sys.argv[5]) if sys.argv[5].isdigit() else 0

AF_QIPCRTR = 42
QRTR_PORT_CTRL = 0xfffffffe
QRTR_TYPE_NEW_SERVER = 4
QRTR_TYPE_NEW_LOOKUP = 10
QMI_SERVICE_VOICE = 9
QMI_SERVICE_UIM = 11

def lookup_qmi_service(srv_id):
  ls = socket.socket(AF_QIPCRTR, socket.SOCK_DGRAM)
  node, _ = ls.getsockname()
  ls.sendto(struct.pack("<IIIII", QRTR_TYPE_NEW_LOOKUP, srv_id, 0, 0, 0), (node, QRTR_PORT_CTRL))
  addr = None
  while True:
    r, _, _ = select.select([ls], [], [], 0.08)
    if not r:
      break
    data, _ = ls.recvfrom(256)
    if len(data) >= 20:
      cmd, srv, inst, srv_node, srv_port = struct.unpack("<IIIII", data[:20])
      if cmd == QRTR_TYPE_NEW_SERVER:
        if srv == srv_id and srv_port != 0:
          addr = (srv_node, srv_port)
        if srv == 0 and srv_node == 0 and srv_port == 0:
          break
  ls.close()
  return addr

v_addr = lookup_qmi_service(QMI_SERVICE_VOICE)
if not v_addr:
  sys.exit(1)

if sub_cmd in ("call-dial", "call-list"):
  u_addr = lookup_qmi_service(QMI_SERVICE_UIM)
  if u_addr:
    try:
      us = socket.socket(AF_QIPCRTR, socket.SOCK_DGRAM)
      us.sendto(struct.pack("<BHHH", 0x00, 1, 0x002F, 0), u_addr)
      r, _, _ = select.select([us], [], [], 0.08)
      if r:
        resp, _ = us.recvfrom(2048)
        pos = 7
        while pos + 3 <= len(resp):
          tt, tl = struct.unpack("<BH", resp[pos:pos+3])
          pos += 3
          val = resp[pos:pos+tl]
          pos += tl
          if tt == 0x10 and len(val) >= 8:
            gw_pri, _, gw_sec, _ = struct.unpack("<HHHH", val[:8])
            if gw_pri != 0xFFFF:
              prim_slot = ((gw_pri >> 8) & 0xFF) + 1
            if gw_sec != 0xFFFF:
              sec_slot = ((gw_sec >> 8) & 0xFF) + 1
      us.close()
    except Exception:
      pass

def parse_tlvs(resp):
  res = {}
  pos = 7
  while pos + 3 <= len(resp):
    tt, tl = struct.unpack("<BH", resp[pos:pos+3])
    pos += 3
    res[tt] = resp[pos:pos+tl]
    pos += tl
  return res

def qmi_req(s, txn, msg_id, tlvs=b"", timeout=3.0):
  s.sendto(struct.pack("<BHHH", 0x00, txn, msg_id, len(tlvs)) + tlvs, v_addr)
  while True:
    r, _, _ = select.select([s], [], [], timeout)
    if not r:
      return {}
    resp, _ = s.recvfrom(2048)
    if len(resp) >= 7 and resp[0] == 0x02:
      r_txn, r_msg, _ = struct.unpack("<HHH", resp[1:7])
      if r_txn == txn and r_msg == msg_id:
        return parse_tlvs(resp)

def parse_call_info(tlvs):
  calls = {}
  raw_ci = tlvs[0x01] if 0x01 in tlvs else tlvs.get(0x10, b"")
  if len(raw_ci) >= 1:
    cnt = raw_ci[0]
    off = 1
    for _ in range(cnt):
      if off + 7 > len(raw_ci):
        break
      cid, cstate, ctype, cdir, cmode, _, _ = struct.unpack("<BBBBBbB", raw_ci[off:off+7])
      off += 7
      calls[cid] = {"id": cid, "state": cstate, "dir": cdir, "num": ""}
  raw_num = tlvs.get(0x10, b"") if 0x01 in tlvs else tlvs.get(0x11, b"")
  if len(raw_num) >= 1:
    cnt = raw_num[0]
    off = 1
    for _ in range(cnt):
      if off + 3 > len(raw_num):
        break
      cid, _, nlen = struct.unpack("<BBB", raw_num[off:off+3])
      off += 3
      num = raw_num[off:off+nlen].decode("ascii", errors="ignore").strip("\x00 ")
      off += nlen
      if cid in calls:
        calls[cid]["num"] = num
  return calls

STATE_MAP = {
  1: "dialing",
  2: "ringing-in",
  3: "active",
  4: "dialing",
  5: "ringing-out",
  6: "held",
  7: "waiting",
  8: "terminated",
  9: "terminated",
  10: "setup",
}

def is_hangup_requested():
  try:
    return (time.time() - os.path.getmtime("/tmp/sxmo_hangup_requested")) < 3.5
  except Exception:
    return False

if sub_cmd == "call-dial":
  if is_hangup_requested():
    sys.exit(1)
  req_slot = int(arg1) if arg1.isdigit() else prim_slot
  sub = 1 if (req_slot == sec_slot and sec_slot != 0) else 0
  num = "".join(c for c in arg2 if c in "+0123456789*#").encode("ascii")
  if not num:
    sys.exit(1)
  calls_dir = "/run/user/10000/sxmo_calls"
  dial_marker = os.path.join(calls_dir, f"sub{sub}_dialing.initiatedcall")
  try:
    os.makedirs(calls_dir, exist_ok=True)
    open(dial_marker, "w").close()
    os.chown(dial_marker, 10000, 10000)
  except Exception:
    pass
  s = socket.socket(AF_QIPCRTR, socket.SOCK_DGRAM)
  qmi_req(s, 1, 0x0044, struct.pack("<BHB", 0x01, 1, sub))
  tlvs = qmi_req(s, 2, 0x0020, struct.pack("<BH", 0x01, len(num)) + num, timeout=5.0)
  res_tlv = tlvs.get(0x02, b"")
  cid = tlvs.get(0x10, b"\x01")[0]
  if is_hangup_requested():
    qmi_req(s, 3, 0x0021, struct.pack("<BHB", 0x01, 1, cid), timeout=0.5)
    s.close()
    try:
      if os.path.exists(dial_marker):
        os.remove(dial_marker)
    except Exception:
      pass
    sys.exit(1)
  s.close()
  if len(res_tlv) >= 4 and struct.unpack("<HH", res_tlv[:4]) == (0, 0):
    import subprocess
    subprocess.run(["dbus-send", "--system", "--type=signal", "/", "org.ofono.VoiceCallManager.CallAdded"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    prefix = f"sub{sub}_"
    try:
      cid_marker = os.path.join(calls_dir, f"{prefix}{cid}.initiatedcall")
      open(cid_marker, "w").close()
      os.chown(cid_marker, 10000, 10000)
      if os.path.exists(dial_marker):
        os.remove(dial_marker)
    except Exception:
      pass
    print(f"{prefix}{cid}")
    sys.exit(0)
  try:
    if os.path.exists(dial_marker):
      os.remove(dial_marker)
  except Exception:
    pass
  sys.exit(1)

elif sub_cmd in ("call-accept", "call-hangup", "call-dtmf"):
  import subprocess
  if sub_cmd == "call-hangup" and arg1 in ("", "-", "all"):
    any_ended = False
    txn = 1
    for sub in (1, 0):
      s = socket.socket(AF_QIPCRTR, socket.SOCK_DGRAM)
      qmi_req(s, txn, 0x0044, struct.pack("<BHB", 0x01, 1, sub), timeout=0.4)
      txn += 1
      calls = parse_call_info(qmi_req(s, txn, 0x002F, timeout=0.5))
      txn += 1
      ended_on_sub = False
      for cid, c in calls.items():
        if c["state"] not in (8, 9):
          tlvs = qmi_req(s, txn, 0x0021, struct.pack("<BHB", 0x01, 1, cid), timeout=0.5)
          txn += 1
          ended_on_sub = True
          res_tlv = tlvs.get(0x02, b"")
          if len(res_tlv) >= 4 and struct.unpack("<HH", res_tlv[:4]) == (0, 0):
            any_ended = True
      if not ended_on_sub:
        tlvs = qmi_req(s, txn, 0x0021, struct.pack("<BHB", 0x01, 1, 1), timeout=0.3)
        txn += 1
        res_tlv = tlvs.get(0x02, b"")
        if len(res_tlv) >= 4 and struct.unpack("<HH", res_tlv[:4]) == (0, 0):
          any_ended = True
      s.close()
    if any_ended:
      subprocess.run(["dbus-send", "--system", "--type=signal", "/", "org.ofono.VoiceCallManager.CallRemoved"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
      sys.exit(0)
    sys.exit(1)

  # Target sub=1 by default or parse sub1_<id>
  target_sub = 1
  target_cid = 0
  if arg1.startswith("sub0_"):
    target_sub = 0
    try:
      target_cid = int(arg1.split("_", 1)[1])
    except Exception:
      target_cid = 0
  elif arg1.startswith("sub1_"):
    target_sub = 1
    try:
      target_cid = int(arg1.split("_", 1)[1])
    except Exception:
      target_cid = 0
  elif arg1.isdigit() and sub_cmd != "call-dtmf":
    target_cid = int(arg1)

  s = socket.socket(AF_QIPCRTR, socket.SOCK_DGRAM)
  qmi_req(s, 1, 0x0044, struct.pack("<BHB", 0x01, 1, target_sub), timeout=0.4)
  calls = parse_call_info(qmi_req(s, 2, 0x002F, timeout=0.5))
  if target_cid == 0 or (sub_cmd == "call-hangup" and target_cid not in calls):
    fallback_cid = target_cid if target_cid > 0 else 1
    target_cid = 0
    for cid, c in calls.items():
      if sub_cmd == "call-accept" and c["state"] in (2, 7):
        target_cid = cid
        break
      elif sub_cmd != "call-accept" and c["state"] not in (8, 9):
        target_cid = cid
        break
    if target_cid == 0 and sub_cmd == "call-hangup":
      target_cid = fallback_cid
  if target_cid == 0:
    s.close()
    sys.exit(1)

  if sub_cmd == "call-accept":
    subprocess.run(["dbus-send", "--system", "--type=signal", "/", "org.ofono.VoiceCallManager.CallAdded"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    tlvs = qmi_req(s, 3, 0x0022, struct.pack("<BHB", 0x01, 1, target_cid))
  elif sub_cmd == "call-hangup":
    tlvs = qmi_req(s, 3, 0x0021, struct.pack("<BHB", 0x01, 1, target_cid))
    txn = 4
    for cid, c in calls.items():
      if cid != target_cid and c["state"] not in (8, 9):
        qmi_req(s, txn, 0x0021, struct.pack("<BHB", 0x01, 1, cid))
        txn += 1
    subprocess.run(["dbus-send", "--system", "--type=signal", "/", "org.ofono.VoiceCallManager.CallRemoved"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
  else:
    ch = (arg1[-1] if arg1 else "0").encode("ascii")[:1]
    payload = struct.pack("<BB", target_cid, 1) + ch
    tlvs = qmi_req(s, 3, 0x0028, struct.pack("<BH", 0x01, len(payload)) + payload)
  s.close()
  res_tlv = tlvs.get(0x02, b"")
  if len(res_tlv) >= 4 and struct.unpack("<HH", res_tlv[:4]) == (0, 0):
    sys.exit(0)
  sys.exit(1)

elif sub_cmd == "call-list":
  s = socket.socket(AF_QIPCRTR, socket.SOCK_DGRAM)
  qmi_req(s, 1, 0x0044, struct.pack("<BHB", 0x01, 1, 1))
  calls = parse_call_info(qmi_req(s, 2, 0x002F))
  s.close()
  for cid, c in calls.items():
    st = STATE_MAP.get(c["state"], "unknown")
    if st != "terminated":
      d_str = "incoming" if c["dir"] == 2 else "outgoing"
      print(f"sub1_{cid}\t{st}\t{d_str}\t{c['num']}\t{sec_slot}")
PY
    exit $?
    ;;

  dsds-daemon)
    exec /usr/bin/bananarchy-dsds
    ;;

  sim-contacts-import)
    req_slot="${2:-auto}"
    if ! wait_for_qmicli_modem 3; then
      echo "ERROR: No modem available"
      exit 1
    fi
    QMI_CARDS="$($QMICLI_MODEM --uim-get-card-status 2>/dev/null || true)"
    if [ -z "$QMI_CARDS" ]; then
      echo "ERROR: Cannot read SIM card status"
      exit 1
    fi
    eval "$(parse_uim_card_status "$QMI_CARDS" "$PREFERRED_SIM_SLOT")"

    target_slot=""
    target_aid=""
    if [ "$req_slot" = "1" ]; then
      if [ "$SLOT1_STATE" != "present" ]; then
        echo "ERROR: SIM 1 is not inserted"
        exit 1
      fi
      target_slot="1"
      target_aid="$SLOT1_AID"
    elif [ "$req_slot" = "2" ]; then
      if [ "$SLOT2_STATE" != "present" ]; then
        echo "ERROR: SIM 2 is not inserted"
        exit 1
      fi
      target_slot="2"
      target_aid="$SLOT2_AID"
    else
      if [ "$PRIMARY_GW_SLOT" = "1" ] && [ "$SLOT1_STATE" = "present" ]; then
        target_slot="1"
        target_aid="$SLOT1_AID"
      elif [ "$PRIMARY_GW_SLOT" = "2" ] && [ "$SLOT2_STATE" = "present" ]; then
        target_slot="2"
        target_aid="$SLOT2_AID"
      elif [ "$SLOT1_STATE" = "present" ]; then
        target_slot="1"
        target_aid="$SLOT1_AID"
      elif [ "$SLOT2_STATE" = "present" ]; then
        target_slot="2"
        target_aid="$SLOT2_AID"
      else
        echo "ERROR: No SIM card detected"
        exit 1
      fi
    fi

    tmp_contacts="/tmp/sim_import_$$.tsv"
    rm -f "$tmp_contacts"
    : > "$tmp_contacts"

    # Method 1: Fast direct QRTR QMI UIM EF_ADN read (supports SIM 1 & SIM 2 without switching GW session)
    if command -v python3 >/dev/null 2>&1; then
      python3 - "$target_slot" > "$tmp_contacts" 2>/dev/null << 'PY' || true
import socket, struct, select, sys

slot = int(sys.argv[1]) if len(sys.argv) > 1 and sys.argv[1].isdigit() else 1
AF_QIPCRTR = 42
QRTR_PORT_CTRL = 0xfffffffe
QRTR_TYPE_NEW_SERVER = 4
QRTR_TYPE_NEW_LOOKUP = 10
QMI_SERVICE_UIM = 11

ls = socket.socket(AF_QIPCRTR, socket.SOCK_DGRAM)
node, _ = ls.getsockname()
ls.sendto(struct.pack("<IIIII", QRTR_TYPE_NEW_LOOKUP, QMI_SERVICE_UIM, 0, 0, 0), (node, QRTR_PORT_CTRL))
uim_addr = None
while True:
    r, _, _ = select.select([ls], [], [], 0.15)
    if not r: break
    data, _ = ls.recvfrom(256)
    if len(data) >= 20:
        cmd, srv, inst, srv_node, srv_port = struct.unpack("<IIIII", data[:20])
        if cmd == QRTR_TYPE_NEW_SERVER:
            if srv == QMI_SERVICE_UIM and srv_port != 0:
                uim_addr = (srv_node, srv_port)
            if srv == 0 and srv_node == 0 and srv_port == 0:
                break
ls.close()
if not uim_addr:
    sys.exit(1)

s = socket.socket(AF_QIPCRTR, socket.SOCK_DGRAM)
session_type = 7 if slot == 2 else 6
tlv_f = None
rec_size = 0
rec_count = 0
txn = 1

for stype in [session_type, 0]:
    for fid, path in [(0x6F3A, [0x3F00, 0x7F10]), (0x4F3A, [0x3F00, 0x7F10, 0x5F3A])]:
        pbytes = b"".join(struct.pack("<H", x) for x in path)
        fval = struct.pack("<HB", fid, len(pbytes)) + pbytes
        tf = struct.pack("<BH", 0x02, len(fval)) + fval
        ts = struct.pack("<BHB", 0x01, 2, stype) + b"\x00"
        tlvs = ts + tf
        s.sendto(struct.pack("<BHHH", 0x00, txn, 0x0024, len(tlvs)) + tlvs, uim_addr)
        txn += 1
        r, _, _ = select.select([s], [], [], 0.15)
        if not r: continue
        resp, _ = s.recvfrom(512)
        if len(resp) < 14 or resp[0] != 0x02 or resp[3] != 0x24: continue
        pos = 7
        ok = False
        rs = rc = 0
        while pos + 3 <= len(resp):
            tt, tl = struct.unpack("<BH", resp[pos:pos+3])
            pos += 3
            if tt == 0x02 and tl >= 4:
                res, err = struct.unpack("<HH", resp[pos:pos+4])
                if res == 0 and err == 0: ok = True
            elif tt == 0x11 and tl >= 9:
                _, _, _, rs, rc = struct.unpack("<HHBHH", resp[pos:pos+9])
            pos += tl
        if ok and rs >= 14 and rc >= 1:
            session_type = stype
            tlv_f = tf
            rec_size = rs
            rec_count = min(rc, 500)
            break
    if tlv_f:
        break

if not tlv_f:
    s.close()
    sys.exit(1)

tlv_session = struct.pack("<BHB", 0x01, 2, session_type) + b"\x00"
bcd_map = "0123456789*#p"

for rnum in range(1, rec_count + 1):
    tlv_rec = struct.pack("<BHHH", 0x03, 4, rnum, rec_size)
    tlvs = tlv_session + tlv_f + tlv_rec
    s.sendto(struct.pack("<BHHH", 0x00, txn, 0x0021, len(tlvs)) + tlvs, uim_addr)
    txn += 1
    r, _, _ = select.select([s], [], [], 0.15)
    if not r: continue
    resp, _ = s.recvfrom(512)
    pos = 7
    raw = None
    ok = False
    while pos + 3 <= len(resp):
        tt, tl = struct.unpack("<BH", resp[pos:pos+3])
        pos += 3
        if tt == 0x02 and tl >= 4:
            res, err = struct.unpack("<HH", resp[pos:pos+4])
            if res == 0 and err == 0: ok = True
        elif tt == 0x11 and tl >= 2:
            clen = struct.unpack("<H", resp[pos:pos+2])[0]
            raw = resp[pos+2:pos+2+clen]
        pos += tl
    if not (ok and raw and len(raw) >= 14):
        continue
    alpha_len = len(raw) - 14
    alpha = raw[:alpha_len]
    bcd_len = raw[alpha_len]
    ton_npi = raw[alpha_len + 1]
    if bcd_len == 0 or bcd_len > 11 or bcd_len == 0xFF:
        continue
    num = "+" if ((ton_npi >> 4) & 0x07) == 1 else ""
    for b in raw[alpha_len + 2 : alpha_len + 2 + min(10, bcd_len - 1)]:
        if b == 0xFF: break
        lo = b & 0x0F
        hi = (b >> 4) & 0x0F
        if lo < len(bcd_map): num += bcd_map[lo]
        else: break
        if hi == 0x0F: break
        if hi < len(bcd_map): num += bcd_map[hi]
        else: break
    if not num or num == "+":
        continue
    while alpha and alpha[-1] == 0xFF:
        alpha = alpha[:-1]
    if not alpha:
        name = num
    elif alpha[0] == 0x80:
        u16 = alpha[1:]
        if len(u16) % 2 == 1: u16 = u16[:-1]
        name = u16.decode("utf-16-be", errors="replace").replace("\t", " ").replace("\n", " ").strip()
    else:
        name = "".join(chr(b) for b in alpha if 32 <= b < 127 and b != 9).strip()
    print(f"{num}\t{name or num}")
s.close()
PY
    fi

    if [ -s "$tmp_contacts" ]; then
      cat "$tmp_contacts"
      rm -f "$tmp_contacts"
      exit 0
    fi

    orig_gw_slot="$PRIMARY_GW_SLOT"
    orig_gw_aid=""
    if [ "$orig_gw_slot" = "1" ]; then
      orig_gw_aid="$SLOT1_AID"
    elif [ "$orig_gw_slot" = "2" ]; then
      orig_gw_aid="$SLOT2_AID"
    fi
    switched_gw=0
    restore_gw_slot() {
      if [ "$switched_gw" = "1" ]; then
        $QMICLI_MODEM --uim-change-provisioning-session='activate=no,session-type=primary-gw-provisioning' >/dev/null 2>&1 || true
        if [ -n "$orig_gw_slot" ] && [ "$orig_gw_slot" != "0" ] && [ -n "$orig_gw_aid" ]; then
          $QMICLI_MODEM --uim-change-provisioning-session="slot=$orig_gw_slot,activate=yes,session-type=primary-gw-provisioning,aid=$orig_gw_aid" >/dev/null 2>&1 || true
        fi
        switched_gw=0
      fi
    }
    trap restore_gw_slot EXIT INT TERM

    if [ "$PRIMARY_GW_SLOT" != "$target_slot" ] && [ -n "$target_aid" ]; then
      if [ "$PRIMARY_GW_SLOT" != "0" ]; then
        $QMICLI_MODEM --uim-change-provisioning-session='activate=no,session-type=primary-gw-provisioning' >/dev/null 2>&1 || true
      fi
      if $QMICLI_MODEM --uim-change-provisioning-session="slot=$target_slot,activate=yes,session-type=primary-gw-provisioning,aid=$target_aid" >/dev/null 2>&1; then
        switched_gw=1
        sleep 1
      fi
    fi

    # Method 2: Direct qmicli UIM EF_ADN (3F00-7F10-6F3A) record fallback
    if [ ! -s "$tmp_contacts" ]; then
      adn_attr="$($QMICLI_MODEM --uim-get-file-attributes=0x3F00,0x7F10,0x6F3A 2>/dev/null || true)"
      reclen="$(printf "%s\n" "$adn_attr" | awk '/Record (size|length):/ {gsub(/[^0-9]/, "", $NF); print $NF + 0; exit}')"
      reccount="$(printf "%s\n" "$adn_attr" | awk '/Record count:/ {gsub(/[^0-9]/, "", $NF); print $NF + 0; exit}')"
      if [ -n "$reclen" ] && [ -n "$reccount" ] && [ "$reclen" -ge 14 ] 2>/dev/null && [ "$reccount" -ge 1 ] 2>/dev/null; then
        if [ "$reccount" -gt 250 ]; then
          reccount=250
        fi
        rec=1
        while [ "$rec" -le "$reccount" ]; do
          raw_rec="$($QMICLI_MODEM --uim-read-record="file=0x3F00-0x7F10-0x6F3A,record-number=${rec},record-length=${reclen}" 2>/dev/null || true)"
          if [ -n "$raw_rec" ]; then
            printf "%s\n" "$raw_rec" | awk '
              function hex2val(h,   i, c, v, res) {
                res = 0
                h = toupper(h)
                for (i = 1; i <= length(h); i++) {
                  c = substr(h, i, 1)
                  v = index("0123456789ABCDEF", c) - 1
                  if (v < 0) return -1
                  res = res * 16 + v
                }
                return res
              }
              function bcd_digit(n) {
                if (n >= 0 && n <= 9) return "" n
                if (n == 10) return "*"
                if (n == 11) return "#"
                return ""
              }
              /Read result:/ { in_res = 1; full = ""; next }
              in_res && /^[[:space:]]*[0-9A-Fa-f]{2}(:[0-9A-Fa-f]{2})*:?[[:space:]]*$/ {
                line = $0
                gsub(/^[[:space:]]+|[[:space:]]+$/, "", line)
                sub(/:$/, "", line)
                full = (full == "") ? line : (full ":" line)
              }
              END {
                if (full == "") exit
                n = split(full, hex, ":")
                if (n < 14) exit
                alpha_len = n - 14
                bcd_len = hex2val(hex[alpha_len + 1])
                ton_npi = hex2val(hex[alpha_len + 2])
                if (bcd_len <= 0 || bcd_len > 11 || bcd_len == 255) exit
                num = ""
                if (int(ton_npi / 16) % 8 == 1) {
                  num = "+"
                }
                bcd_bytes = bcd_len - 1
                if (bcd_bytes > 10) bcd_bytes = 10
                for (i = 1; i <= bcd_bytes; i++) {
                  b = hex2val(hex[alpha_len + 2 + i])
                  if (b < 0 || b == 255) break
                  lo = b % 16
                  hi = int(b / 16)
                  d1 = bcd_digit(lo)
                  if (d1 == "") break
                  num = num d1
                  d2 = bcd_digit(hi)
                  if (d2 == "") break
                  num = num d2
                }
                if (num == "" || num == "+") exit
                name = ""
                for (i = 1; i <= alpha_len; i++) {
                  b = hex2val(hex[i])
                  if (b < 0 || b == 255) break
                  if (b >= 32 && b < 127 && b != 9) {
                    name = name sprintf("%c", b)
                  }
                }
                gsub(/^[[:space:]]+|[[:space:]]+$/, "", name)
                if (name == "") name = num
                printf "%s\t%s\n", num, name
              }
            ' >> "$tmp_contacts"
          fi
          rec=$((rec + 1))
        done
      fi
    fi

    cat "$tmp_contacts"
    rm -f "$tmp_contacts"
    exit 0
    ;;

  sim-contacts-export)
    req_slot="${2:-auto}"
    src_tsv="${3:-/home/user/.config/sxmo/contacts.tsv}"
    if [ ! -r "$src_tsv" ]; then
      echo "ERROR: Contacts file not found"
      exit 1
    fi
    if ! wait_for_qmicli_modem 3; then
      echo "ERROR: No modem available"
      exit 1
    fi
    QMI_CARDS="$($QMICLI_MODEM --uim-get-card-status 2>/dev/null || true)"
    if [ -z "$QMI_CARDS" ]; then
      echo "ERROR: Cannot read SIM card status"
      exit 1
    fi
    eval "$(parse_uim_card_status "$QMI_CARDS" "$PREFERRED_SIM_SLOT")"

    target_slot=""
    target_aid=""
    if [ "$req_slot" = "1" ]; then
      if [ "$SLOT1_STATE" != "present" ]; then
        echo "ERROR: SIM 1 is not inserted"
        exit 1
      fi
      target_slot="1"
      target_aid="$SLOT1_AID"
    elif [ "$req_slot" = "2" ]; then
      if [ "$SLOT2_STATE" != "present" ]; then
        echo "ERROR: SIM 2 is not inserted"
        exit 1
      fi
      target_slot="2"
      target_aid="$SLOT2_AID"
    else
      if [ "$PRIMARY_GW_SLOT" = "1" ] && [ "$SLOT1_STATE" = "present" ]; then
        target_slot="1"
        target_aid="$SLOT1_AID"
      elif [ "$PRIMARY_GW_SLOT" = "2" ] && [ "$SLOT2_STATE" = "present" ]; then
        target_slot="2"
        target_aid="$SLOT2_AID"
      elif [ "$SLOT1_STATE" = "present" ]; then
        target_slot="1"
        target_aid="$SLOT1_AID"
      elif [ "$SLOT2_STATE" = "present" ]; then
        target_slot="2"
        target_aid="$SLOT2_AID"
      else
        echo "ERROR: No SIM card detected"
        exit 1
      fi
    fi

    if command -v python3 >/dev/null 2>&1; then
      exp_out="$(python3 - "$target_slot" "$src_tsv" << 'PY'
import socket, struct, select, sys

slot = int(sys.argv[1]) if len(sys.argv) > 1 and sys.argv[1].isdigit() else 1
tsv_path = sys.argv[2]

rows = []
with open(tsv_path, "r", encoding="utf-8", errors="replace") as f:
    for line in f:
        line = line.rstrip("\r\n")
        if "\t" not in line: continue
        num, name = line.split("\t", 1)
        num = "".join(c for c in num if c in "+0123456789*#")
        name = name.strip()
        if num:
            rows.append((num, name or num))

if not rows:
    print("ERROR: No contacts to export")
    sys.exit(1)

AF_QIPCRTR = 42
QRTR_PORT_CTRL = 0xfffffffe
QRTR_TYPE_NEW_SERVER = 4
QRTR_TYPE_NEW_LOOKUP = 10
QMI_SERVICE_UIM = 11

ls = socket.socket(AF_QIPCRTR, socket.SOCK_DGRAM)
node, _ = ls.getsockname()
ls.sendto(struct.pack("<IIIII", QRTR_TYPE_NEW_LOOKUP, QMI_SERVICE_UIM, 0, 0, 0), (node, QRTR_PORT_CTRL))
uim_addr = None
while True:
    r, _, _ = select.select([ls], [], [], 0.15)
    if not r: break
    data, _ = ls.recvfrom(256)
    if len(data) >= 20:
        cmd, srv, inst, srv_node, srv_port = struct.unpack("<IIIII", data[:20])
        if cmd == QRTR_TYPE_NEW_SERVER:
            if srv == QMI_SERVICE_UIM and srv_port != 0:
                uim_addr = (srv_node, srv_port)
            if srv == 0 and srv_node == 0 and srv_port == 0:
                break
ls.close()
if not uim_addr:
    print("ERROR: Modem UIM service unavailable")
    sys.exit(1)

s = socket.socket(AF_QIPCRTR, socket.SOCK_DGRAM)
session_type = 7 if slot == 2 else 6
tlv_f = None
rec_size = 0
rec_count = 0
txn = 1

for stype in [session_type, 0]:
    for fid, path in [(0x6F3A, [0x3F00, 0x7F10]), (0x4F3A, [0x3F00, 0x7F10, 0x5F3A])]:
        pbytes = b"".join(struct.pack("<H", x) for x in path)
        fval = struct.pack("<HB", fid, len(pbytes)) + pbytes
        tf = struct.pack("<BH", 0x02, len(fval)) + fval
        ts = struct.pack("<BHB", 0x01, 2, stype) + b"\x00"
        tlvs = ts + tf
        s.sendto(struct.pack("<BHHH", 0x00, txn, 0x0024, len(tlvs)) + tlvs, uim_addr)
        txn += 1
        r, _, _ = select.select([s], [], [], 0.15)
        if not r: continue
        resp, _ = s.recvfrom(512)
        if len(resp) < 14 or resp[0] != 0x02 or resp[3] != 0x24: continue
        pos = 7
        ok = False
        rs = rc = 0
        while pos + 3 <= len(resp):
            tt, tl = struct.unpack("<BH", resp[pos:pos+3])
            pos += 3
            if tt == 0x02 and tl >= 4:
                res, err = struct.unpack("<HH", resp[pos:pos+4])
                if res == 0 and err == 0: ok = True
            elif tt == 0x11 and tl >= 9:
                _, _, _, rs, rc = struct.unpack("<HHBHH", resp[pos:pos+9])
            pos += tl
        if ok and rs >= 14 and rc >= 1:
            session_type = stype
            tlv_f = tf
            rec_size = rs
            rec_count = min(rc, 500)
            break
    if tlv_f:
        break

if not tlv_f:
    s.close()
    print(f"ERROR: SIM {slot} phonebook not ready")
    sys.exit(1)

tlv_session = struct.pack("<BHB", 0x01, 2, session_type) + b"\x00"
bcd_map_str = "0123456789*#p"
existing_by_norm = {}
existing_by_sfx = {}
empty_slots = []

def sfx_key(norm):
    d = "".join(c for c in norm if c.isdigit())
    return d[-9:] if len(d) >= 9 else norm

for rnum in range(1, rec_count + 1):
    tlv_rec = struct.pack("<BHHH", 0x03, 4, rnum, rec_size)
    tlvs = tlv_session + tlv_f + tlv_rec
    s.sendto(struct.pack("<BHHH", 0x00, txn, 0x0021, len(tlvs)) + tlvs, uim_addr)
    txn += 1
    r, _, _ = select.select([s], [], [], 0.15)
    if not r: continue
    resp, _ = s.recvfrom(512)
    pos = 7
    raw = None
    ok = False
    while pos + 3 <= len(resp):
        tt, tl = struct.unpack("<BH", resp[pos:pos+3])
        pos += 3
        if tt == 0x02 and tl >= 4:
            res, err = struct.unpack("<HH", resp[pos:pos+4])
            if res == 0 and err == 0: ok = True
        elif tt == 0x11 and tl >= 2:
            clen = struct.unpack("<H", resp[pos:pos+2])[0]
            raw = resp[pos+2:pos+2+clen]
        pos += tl
    if not (ok and raw and len(raw) >= 14):
        continue
    alpha_len = len(raw) - 14
    bcd_len = raw[alpha_len]
    ton_npi = raw[alpha_len + 1]
    if bcd_len == 0 or bcd_len > 11 or bcd_len == 0xFF:
        empty_slots.append(rnum)
        continue
    num = "+" if ((ton_npi >> 4) & 0x07) == 1 else ""
    for b in raw[alpha_len + 2 : alpha_len + 2 + min(10, bcd_len - 1)]:
        if b == 0xFF: break
        lo = b & 0x0F
        hi = (b >> 4) & 0x0F
        if lo < len(bcd_map_str): num += bcd_map_str[lo]
        else: break
        if hi == 0x0F: break
        if hi < len(bcd_map_str): num += bcd_map_str[hi]
        else: break
    if not num or num == "+":
        empty_slots.append(rnum)
        continue
    existing_by_norm[num] = rnum
    existing_by_sfx[sfx_key(num)] = rnum

def encode_adn(name, num, rsize):
    alpha_len = rsize - 14
    try:
        nb = name.encode("ascii")[:alpha_len]
        alpha = nb + b"\xFF" * (alpha_len - len(nb))
    except UnicodeEncodeError:
        u16 = name.encode("utf-16-be")[:max(0, (alpha_len - 1) // 2 * 2)]
        alpha = b"\x80" + u16 + b"\xFF" * (alpha_len - 1 - len(u16))
    ton_npi = 0x91 if num.startswith("+") else 0x81
    digits = [c for c in num if c != "+"][:20]
    if not digits: return None
    bcd = bytearray([0xFF] * 10)
    bmap = {str(i): i for i in range(10)}
    bmap["*"] = 0x0A
    bmap["#"] = 0x0B
    for idx, ch in enumerate(digits):
        nib = bmap.get(ch, 0x0F)
        bi = idx // 2
        if idx % 2 == 0:
            bcd[bi] = (bcd[bi] & 0xF0) | nib
        else:
            bcd[bi] = (bcd[bi] & 0x0F) | (nib << 4)
    bcd_len = 1 + (len(digits) + 1) // 2
    return alpha + bytes([bcd_len, ton_npi]) + bytes(bcd) + b"\xFF\xFF"

exported = 0
empty_idx = 0
for num, name in rows:
    trec = existing_by_norm.get(num) or existing_by_sfx.get(sfx_key(num))
    if not trec:
        if empty_idx < len(empty_slots):
            trec = empty_slots[empty_idx]
            empty_idx += 1
        else:
            break
    rdata = encode_adn(name, num, rec_size)
    if not rdata: continue
    wval = struct.pack("<HH", trec, len(rdata)) + rdata
    tlv_w = struct.pack("<BH", 0x03, len(wval)) + wval
    tlvs = tlv_session + tlv_f + tlv_w
    s.sendto(struct.pack("<BHHH", 0x00, txn, 0x0023, len(tlvs)) + tlvs, uim_addr)
    txn += 1
    r, _, _ = select.select([s], [], [], 0.2)
    if not r: continue
    resp, _ = s.recvfrom(512)
    pos = 7
    ok = False
    while pos + 3 <= len(resp):
        tt, tl = struct.unpack("<BH", resp[pos:pos+3])
        pos += 3
        if tt == 0x02 and tl >= 4:
            res, err = struct.unpack("<HH", resp[pos:pos+4])
            if res == 0 and err == 0: ok = True
        pos += tl
    if ok:
        exported += 1
        existing_by_norm[num] = trec
        existing_by_sfx[sfx_key(num)] = trec

s.close()
if exported == 0 and empty_idx >= len(empty_slots):
    print(f"ERROR: SIM {slot} phonebook is full")
    sys.exit(1)
print(f"EXPORTED={exported}")
print(f"SLOT={slot}")
PY
)"
      if printf "%s\n" "$exp_out" | grep -q "^EXPORTED="; then
        printf "%s\n" "$exp_out"
        exit 0
      fi
      if printf "%s\n" "$exp_out" | grep -q "^ERROR:"; then
        printf "%s\n" "$exp_out"
        exit 1
      fi
    fi

    echo "ERROR: SIM $target_slot phonebook not ready"
    exit 1
    ;;

  ensure-ps-domain)
    ensure_dsds_nas_registration auto
    exit 0
    ;;

  sync-apn)
    sync_wds_apn "${2:-}" "${3:-}" "${4:-}"
    exit 0
    ;;

  mobile-data-prep)
    mobile_data_prep "${2:-}" "${3:-}" "${4:-}"
    exit 0
    ;;

  restore-dsds)
    restore_dsds
    exit 0
    ;;

  *)
    echo "Usage: $0 [boot|status|switch <1|2>|ensure-ps-domain|sync-apn [apn] [user] [pass]|mobile-data-prep [apn] [user] [pass]|restore-dsds|verify-pin <slot> <pin>|unblock-puk <slot> <puk> <newpin>|set-pin-lock <slot> <enable|disable> <pin>|change-pin <slot> <oldpin> <newpin>|imei|usb-tether <on|off|status>|at <port> <cmd>|sim-contacts-import [1|2|auto]|sim-contacts-export [1|2|auto] [tsv_file]]" >&2
    exit 1
    ;;
esac
