#!/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_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 ! command -v qmicli >/dev/null 2>&1; then
    return 1
  fi
  if [ -e "/dev/wwan0qmi0" ]; then
    if timeout 3 qmicli --silent -pd /dev/wwan0qmi0 --device-open-qmi --uim-noop >/dev/null 2>&1; then
      QMICLI_MODEM="timeout 4 qmicli --silent -pd /dev/wwan0qmi0 --device-open-qmi"
      return 0
    elif timeout 3 qmicli --silent -d /dev/wwan0qmi0 --device-open-qmi --uim-noop >/dev/null 2>&1; then
      QMICLI_MODEM="timeout 4 qmicli --silent -d /dev/wwan0qmi0 --device-open-qmi"
      return 0
    fi
  fi
  if timeout 3 qmicli --silent -pd qrtr://0 --uim-noop >/dev/null 2>&1; then
    QMICLI_MODEM="timeout 4 qmicli --silent -pd qrtr://0"
    return 0
  elif timeout 3 qmicli --silent -d qrtr://0 --uim-noop >/dev/null 2>&1; then
    QMICLI_MODEM="timeout 4 qmicli --silent -d qrtr://0"
    return 0
  elif [ -e "/dev/modem" ]; then
    if timeout 3 qmicli --silent -pd /dev/modem --uim-noop >/dev/null 2>&1; then
      QMICLI_MODEM="timeout 4 qmicli --silent -pd /dev/modem"
      return 0
    elif timeout 3 qmicli --silent -d /dev/modem --uim-noop >/dev/null 2>&1; then
      QMICLI_MODEM="timeout 4 qmicli --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() {
  if ! command -v python3 >/dev/null 2>&1; then
    return 0
  fi
  python3 - << 'PY' >/dev/null 2>&1 || true
import socket, struct, select

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

ls = socket.socket(AF_QIPCRTR, socket.SOCK_DGRAM)
node, _ = ls.getsockname()
ls.sendto(struct.pack("<IIIII", QRTR_TYPE_NEW_LOOKUP, QMI_SERVICE_NAS, 0, 0, 0), (node, QRTR_PORT_CTRL))
nas_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_NAS and srv_port != 0:
        nas_addr = (srv_node, srv_port)
      if srv == 0 and srv_node == 0 and srv_port == 0:
        break
ls.close()
if not nas_addr:
  raise SystemExit(0)

def qmi_req(s, txn, msg_id, tlvs=b""):
  s.sendto(struct.pack("<BHHH", 0x00, txn, msg_id, len(tlvs)) + tlvs, nas_addr)
  r, _, _ = select.select([s], [], [], 0.25)
  if r:
    return s.recvfrom(1024)[0]
  return b""

def get_reg_state(s, txn):
  resp = qmi_req(s, txn, 0x0024)
  pos = 7
  while pos + 3 <= len(resp):
    tt, tl = struct.unpack("<BH", resp[pos:pos+3])
    pos += 3
    if tt == 0x01 and tl >= 1:
      return resp[pos]
    pos += tl
  return 0

for sub in (0, 1):
  s = socket.socket(AF_QIPCRTR, socket.SOCK_DGRAM)
  qmi_req(s, 1, 0x0045, struct.pack("<BHB", 0x01, 1, sub))
  reg_st = get_reg_state(s, 2)
  if reg_st not in (1, 2):
    if sub == 0:
      qmi_req(s, 3, 0x004B, struct.pack("<BHB", 0x10, 1, 2))
    qmi_req(s, 4, 0x0022, struct.pack("<BHB", 0x01, 1, 1))
  s.close()
PY
}

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

  if ! wait_for_qmicli_modem "$wait_secs"; then
    echo "No modem available." >&2
    return 2
  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")"

  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

  # 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
    ensure_dsds_nas_registration
    printf '1\n' > /tmp/sxmo_dsds_active 2>/dev/null || true
  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
    printf '0\n' > /tmp/sxmo_dsds_active 2>/dev/null || true
  fi
  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 8 ]; 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 10 ]; 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 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
    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
    pkill -f "msm-modem-uim-selection dsds-daemon" 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
        nft add table ip nat 2>/dev/null || true
        nft 'add chain ip nat postrouting { type nat hook postrouting priority 100 ; }' 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.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
    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
        wwan0at0|wwan0at1)
          dev="/dev/$candidate"
          ;;
        /dev/wwan0at0|/dev/wwan0at1)
          dev="$candidate"
          ;;
        *)
          dev=""
          ;;
      esac
      if [ -n "$dev" ] && [ -c "$dev" ]; then
        resp="$(timeout 3 sh -c '
          dev="$1"
          cmd="$2"
          tmpf="/tmp/at_resp_$$.txt"
          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
          tr -d "\r" < "$tmpf" 2>/dev/null || true
          rm -f "$tmpf"
        ' _ "$dev" "$at_cmd" 2>/dev/null | sed '/^[[:space:]]*$/d' || true)"
        if [ -n "$resp" ]; then
          printf "%s\n" "$resp"
          exit 0
        fi
      fi
      if [ "$port" != "auto" ] && [ "$candidate" = "$port" ]; then
        break
      fi
    done
    mm_out="$(mmcli -m any --command="$at_cmd" 2>&1 || true)"
    if [ -n "$mm_out" ]; then
      printf "%s\n" "$mm_out" | sed "s/^response: '\(.*\)'$/\1/"
      exit 0
    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
    # If requested SIM is Secondary GW, use QMI VOICE USSD on sub=1
    if [ "$req_sim" = "$sec_slot" ] && [ "$sec_slot" != "0" ] && command -v python3 >/dev/null 2>&1; then
      qmi_ussd="$(python3 - "$ussd_mode" "$ussd_code" "1" << 'PY' 2>/dev/null || true
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 1
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 [ -n "$qmi_ussd" ]; then
        printf "%s\n" "$qmi_ussd"
        exit 0
      fi
    fi
    if [ "$req_sim" = "$prim_slot" ]; then
      mm_state="$(mmcli -m any -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 any -e >/dev/null 2>&1 || true
        sleep 1
      fi
      modem_dbus_path="$(mmcli -m any -K 2>/dev/null | awk -F':[[:space:]]*' '{gsub(/[[:space:]]+$/, "", $1); if ($1 == "modem.dbus-path") {print $2; exit}}' || true)"
      [ -z "$modem_dbus_path" ] && modem_dbus_path="/org/freedesktop/ModemManager1/Modem/0"
      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 any --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
      mm_out=""
      if [ "$ussd_mode" = "respond" ]; then
        mm_out="$(mmcli --timeout=30 -m any --3gpp-ussd-respond="$ussd_code" 2>&1)" || mm_rc=$?
      else
        if [ "$ussd_st" = "active" ] || [ "$ussd_st" = "user-response" ]; then
          mmcli -m any --3gpp-ussd-cancel >/dev/null 2>&1 || true
        fi
        mm_out="$(mmcli --timeout=30 -m any --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 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
    if [ -n "${mm_out:-}" ]; then
      printf "%s\n" "$mm_out"
    else
      echo "ERROR: USSD request failed"
    fi
    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 $?
    ;;

  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"
    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
    python3 - "$sub_cmd" "$arg1" "$arg2" "$prim_slot" "$sec_slot" << 'PY'
import select, socket, struct, sys

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

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)

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",
}

if sub_cmd == "call-dial":
  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)
  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)
  s.close()
  res_tlv = tlvs.get(0x02, b"")
  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)
    cid = tlvs.get(0x10, b"\x01")[0]
    prefix = f"sub{sub}_"
    print(f"{prefix}{cid}")
    sys.exit(0)
  sys.exit(1)

elif sub_cmd in ("call-accept", "call-hangup", "call-dtmf"):
  import subprocess
  # Target sub=1 by default or parse sub1_<id>
  target_sub = 1
  target_cid = 0
  if arg1.startswith("sub0_"):
    target_sub = 0
    target_cid = int(arg1.split("_", 1)[1])
  elif arg1.startswith("sub1_"):
    target_sub = 1
    target_cid = int(arg1.split("_", 1)[1])
  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))
  if target_cid == 0:
    calls = parse_call_info(qmi_req(s, 2, 0x002F))
    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:
    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))
    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 python3 - << 'PY'
import datetime, os, select, socket, struct, subprocess, sys, time

try:
  while os.waitpid(-1, os.WNOHANG)[0] > 0:
    pass
except Exception:
  pass

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

CALLS_DIR = "/run/user/10000/sxmo_calls"
LOG_DIR = "/home/user/.local/share/sxmo/modem"
MODEMLOG = os.path.join(LOG_DIR, "modemlog.tsv")

# This daemon runs as root (via doas), but everything it creates under the
# user's runtime and data directories must stay owned by "user": the sxmo
# scripts that run as the user append to modemlog.tsv and create call state
# files under `set -e`, so a root-owned directory or log file makes them
# abort (no call log entries, and rejected calls never get hung up).
try:
  import pwd
  _pw = pwd.getpwnam("user")
  USER_UID, USER_GID = _pw.pw_uid, _pw.pw_gid
except Exception:
  USER_UID, USER_GID = 10000, 10000

def chown_user(path):
  try:
    os.chown(path, USER_UID, USER_GID)
  except Exception:
    pass

def ensure_user_dir(path, stop_at):
  # Create `path` (and missing parents below `stop_at`) owned by the user,
  # and repair ownership of directories a previous root-run instance created.
  parts = []
  cur = path
  while cur and cur != stop_at and cur != "/":
    parts.append(cur)
    cur = os.path.dirname(cur)
  for d in reversed(parts):
    try:
      os.mkdir(d, 0o755)
    except FileExistsError:
      pass
    except Exception:
      return
    try:
      if os.stat(d).st_uid == 0:
        chown_user(d)
    except Exception:
      pass

def append_modemlog(line):
  ensure_user_dir(LOG_DIR, "/home/user")
  try:
    with open(MODEMLOG, "a", encoding="utf-8") as f:
      f.write(line)
  except Exception:
    return
  chown_user(MODEMLOG)

# Only create the call state directory inside an existing user runtime dir;
# never create /run/user/10000 itself as root.
if os.path.isdir("/run/user/10000"):
  ensure_user_dir(CALLS_DIR, "/run/user/10000")
ensure_user_dir(LOG_DIR, "/home/user")
# Repair logs and directories left root-owned by earlier daemon versions.
try:
  for root_dir, dirs, files in os.walk(LOG_DIR):
    for name in dirs + files:
      p = os.path.join(root_dir, name)
      if os.lstat(p).st_uid == 0:
        chown_user(p)
except Exception:
  pass

def lookup_srv(sid):
  try:
    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.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 == 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
  except Exception:
    return None

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

pending_inds = []

def qmi_req(s, addr, txn, msg_id, tlvs=b"", timeout=1.0):
  s.sendto(struct.pack("<BHHH", 0x00, txn, msg_id, len(tlvs)) + tlvs, addr)
  deadline = time.time() + timeout
  while time.time() < deadline:
    r, _, _ = select.select([s], [], [], max(0.05, deadline - time.time()))
    if not r:
      return {}
    resp, _ = s.recvfrom(4096)
    if len(resp) >= 7 and resp[0] == 0x04:
      pending_inds.append((s, resp))
      continue
    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)
  return {}

def run_user_cmd(cmd_str, extra_env=None):
  env = os.environ.copy()
  env["DISPLAY"] = ":0"
  env["XDG_RUNTIME_DIR"] = "/run/user/10000"
  env["HOME"] = "/home/user"
  env["PATH"] = "/usr/share/sxmo/default_hooks:/usr/bin:/bin:/usr/sbin:/sbin"
  if extra_env:
    env.update(extra_env)
  try:
    p = subprocess.Popen(
      ["su", "-m", "user", "-c", f"export DISPLAY=:0 XDG_RUNTIME_DIR=/run/user/10000 HOME=/home/user PATH=/usr/share/sxmo/default_hooks:/usr/bin:/bin:/usr/sbin:/sbin; ({cmd_str}) >/dev/null 2>&1 &"],
      env=env,
      stdout=subprocess.DEVNULL,
      stderr=subprocess.DEVNULL
    )
    p.wait(timeout=2.0)
  except Exception:
    pass

def send_fifo(fifo_path, line):
  try:
    if os.path.exists(fifo_path):
      fd = os.open(fifo_path, os.O_WRONLY | os.O_NONBLOCK)
      os.write(fd, (line + "\n").encode("utf-8"))
      os.close(fd)
  except Exception:
    pass

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 = {
  0x0A: "\f", 0x14: "^", 0x28: "{", 0x29: "}", 0x2F: "\\",
  0x3C: "[", 0x3D: "~", 0x3E: "]", 0x40: "|", 0x65: "\u20ac"
}

def decode_bcd_addr(data, num_digits, ton_npi):
  ton = (ton_npi >> 4) & 0x07
  if ton == 5:
    # Alphanumeric 7-bit GSM address
    total_septets = (num_digits * 4) // 7
    septets = []
    esc = False
    for i in range(total_septets):
      bit_off = i * 7
      byte_idx = bit_off // 8
      shift = bit_off % 8
      if byte_idx >= len(data):
        break
      val = (data[byte_idx] >> shift) & 0x7F
      if shift > 1 and (byte_idx + 1) < len(data):
        val |= (data[byte_idx + 1] << (8 - shift)) & 0x7F
      if esc:
        septets.append(GSM7_EXT.get(val, ""))
        esc = False
      elif val == 0x1B:
        esc = True
      else:
        septets.append(GSM7_BASIC[val] if val < len(GSM7_BASIC) else "")
    return "".join(septets).strip("@ ")
  prefix = "+" if ton == 1 else ""
  digits = []
  for b in data:
    lo = b & 0x0F
    hi = (b >> 4) & 0x0F
    if lo < 10:
      digits.append(str(lo))
    if hi < 10 and len(digits) < num_digits:
      digits.append(str(hi))
  return prefix + "".join(digits[:num_digits])

def _parse_deliver_tpdu(pdu, pos):
  try:
    if pos < 0 or pos + 12 > len(pdu):
      return None
    first_octet = pdu[pos]
    mti = first_octet & 0x03
    if mti != 0:
      return None
    udhi = (first_octet & 0x40) != 0
    pos += 1
    oa_digits = pdu[pos]
    oa_ton_npi = pdu[pos + 1]
    if oa_digits > 24 or (oa_ton_npi & 0x80) == 0:
      return None
    oa_byte_len = (oa_digits + 1) // 2
    if pos + 2 + oa_byte_len + 10 > len(pdu):
      return None
    oa_bytes = pdu[pos + 2 : pos + 2 + oa_byte_len]
    sender = decode_bcd_addr(oa_bytes, oa_digits, oa_ton_npi)
    pos += 2 + oa_byte_len
    pid = pdu[pos]
    dcs = pdu[pos + 1]
    scts = pdu[pos + 2 : pos + 9]
    udl = pdu[pos + 9]
    ud = pdu[pos + 10 :]

    # Validate and decode SCTS (YY MM DD HH MM SS TZ)
    def unbcd(b):
      lo = b & 0x0F
      hi = (b >> 4) & 0x0F
      if lo > 9 or hi > 9:
        raise ValueError("invalid BCD")
      return (lo * 10) + hi

    yr = 2000 + unbcd(scts[0])
    mo = unbcd(scts[1])
    dy = unbcd(scts[2])
    hr = unbcd(scts[3])
    mi = unbcd(scts[4])
    sc = unbcd(scts[5])
    if not (1 <= mo <= 12 and 1 <= dy <= 31 and 0 <= hr <= 23 and 0 <= mi <= 59 and 0 <= sc <= 59):
      return None
    iso_ts = f"{yr:04d}-{mo:02d}-{dy:02d}T{hr:02d}:{mi:02d}:{sc:02d}"

    csms_ref = None
    csms_total = 1
    csms_seq = 1
    udh_bytes = 0
    if udhi and len(ud) >= 1:
      udh_len = ud[0]
      udh_bytes = 1 + udh_len
      if udh_bytes > len(ud):
        return None
      upos = 1
      while upos + 2 <= udh_bytes and upos + 2 <= len(ud):
        iei = ud[upos]
        ielen = ud[upos + 1]
        iedata = ud[upos + 2 : upos + 2 + ielen]
        upos += 2 + ielen
        if iei == 0x00 and len(iedata) >= 3:
          csms_ref, csms_total, csms_seq = iedata[0], iedata[1], iedata[2]
        elif iei == 0x08 and len(iedata) >= 4:
          csms_ref = (iedata[0] << 8) | iedata[1]
          csms_total, csms_seq = iedata[2], iedata[3]
      if csms_ref is not None and (csms_total < 1 or csms_seq < 1 or csms_seq > csms_total):
        csms_ref = None
        csms_total = 1
        csms_seq = 1

    # Determine alphabet from 3GPP TS 23.038 DCS
    if (dcs & 0xC0) in (0x00, 0x40):
      alphabet = (dcs >> 2) & 0x03
      if alphabet == 3:
        alphabet = 0
    elif (dcs & 0xF0) == 0xE0:
      alphabet = 2
    elif (dcs & 0xF0) in (0xC0, 0xD0):
      alphabet = 0
    elif (dcs & 0xF0) == 0xF0:
      alphabet = 1 if (dcs & 0x04) else 0
    else:
      alphabet = 0

    if alphabet == 2:
      end_byte = min(udl, len(ud))
      payload = ud[udh_bytes : end_byte]
      if len(payload) % 2 == 1:
        payload = payload[:-1]
      text = payload.decode("utf-16-be", errors="surrogatepass")
    elif alphabet == 1:
      end_byte = min(udl, len(ud))
      payload = ud[udh_bytes : end_byte]
      text = payload.decode("utf-8", errors="replace")
    else:
      fill_bits = (7 - ((udh_bytes * 8) % 7)) % 7 if udh_bytes > 0 else 0
      start_septet = ((udh_bytes * 8) + fill_bits) // 7
      chars = []
      esc = False
      for i in range(start_septet, udl):
        bit_off = i * 7
        byte_idx = bit_off // 8
        shift = bit_off % 8
        if byte_idx >= len(ud):
          break
        val = (ud[byte_idx] >> shift) & 0x7F
        if shift > 1 and (byte_idx + 1) < len(ud):
          val |= (ud[byte_idx + 1] << (8 - shift)) & 0x7F
        if esc:
          chars.append(GSM7_EXT.get(val, " "))
          esc = False
        elif val == 0x1B:
          esc = True
        else:
          chars.append(GSM7_BASIC[val] if val < len(GSM7_BASIC) else "?")
      text = "".join(chars)

    clean_sender = "".join(
      c for c in (sender or "Unknown")
      if c not in "/\x00\r\n\t" and ord(c) >= 32
    ).strip() or "Unknown"

    return {
      "sender": clean_sender,
      "time": iso_ts,
      "text": text,
      "ref": csms_ref,
      "total": csms_total,
      "seq": csms_seq,
    }
  except Exception:
    return None

def decode_sms_deliver(pdu, only_tpdu=False):
  if not pdu or len(pdu) < 12:
    return None
  if only_tpdu:
    res = _parse_deliver_tpdu(pdu, 0)
    if res is not None:
      return res
    smsc_len = pdu[0]
    if 0 <= smsc_len <= 12 and (smsc_len == 0 or (pdu[1] & 0x80) != 0):
      return _parse_deliver_tpdu(pdu, 1 + smsc_len)
    return None
  smsc_len = pdu[0]
  if 0 <= smsc_len <= 12 and (smsc_len == 0 or (len(pdu) > 1 and (pdu[1] & 0x80) != 0)):
    res = _parse_deliver_tpdu(pdu, 1 + smsc_len)
    if res is not None:
      return res
  return _parse_deliver_tpdu(pdu, 0)

multipart_buf = {}
recent_sms_dedup = {}

def _normalize_sms_text(s):
  try:
    return s.encode("utf-16", "surrogatepass").decode("utf-16", "replace")
  except Exception:
    return s

BLOCK_FILE = "/home/user/.config/sxmo/block.tsv"
BLOCK_DIR = "/home/user/.local/share/sxmo/block"

def is_sender_blocked(sender):
  try:
    if not os.path.isfile(BLOCK_FILE):
      return False
    norm = "".join(c for c in sender if c.isdigit() or c == "+")
    if not norm:
      norm = sender.strip()
    sfx = norm[-7:] if len(norm) >= 7 else ""
    with open(BLOCK_FILE, "r", encoding="utf-8", errors="ignore") as bf:
      for line in bf:
        raw = line.split("\t", 1)[0].strip()
        if not raw:
          continue
        r_norm = "".join(c for c in raw if c.isdigit() or c in "+*")
        if not r_norm:
          continue
        if r_norm.endswith("*") and len(r_norm) > 1:
          if norm.startswith(r_norm[:-1]):
            return True
        elif r_norm == norm or (sfx and len(r_norm) >= 7 and r_norm[-7:] == sfx):
          return True
  except Exception:
    pass
  return False

def deliver_sms_to_sxmo(sender, iso_ts, text, sim_slot):
  now_str = datetime.datetime.now().astimezone().isoformat(timespec="seconds")
  tsv_text = text.replace("\t", " ").replace("\r", " ").replace("\n", " ")
  if is_sender_blocked(sender):
    num_dir = os.path.join(BLOCK_DIR, sender)
    ensure_user_dir(num_dir, "/home/user")
    sms_file = os.path.join(num_dir, "sms.txt")
    header = f"Received from {sender} [SIM {sim_slot}] at {now_str}:\n{text}\n\n"
    with open(sms_file, "a", encoding="utf-8") as f:
      f.write(header)
    chown_user(sms_file)
    blk_log = os.path.join(BLOCK_DIR, "modemlog.tsv")
    try:
      with open(blk_log, "a", encoding="utf-8") as f:
        f.write(f"{now_str}\trecv_txt\t{sender}\t[SIM {sim_slot}] {tsv_text}\n")
      chown_user(blk_log)
    except Exception:
      pass
    send_fifo("/tmp/dwm_plugin_sms.fifo", "REFRESH")
    return

  num_dir = os.path.join(LOG_DIR, sender)
  ensure_user_dir(num_dir, "/home/user")
  sms_file = os.path.join(num_dir, "sms.txt")
  header = f"Received from {sender} [SIM {sim_slot}] at {now_str}:\n{text}\n\n"
  with open(sms_file, "a", encoding="utf-8") as f:
    f.write(header)
  append_modemlog(f"{now_str}\trecv_txt\t{sender}\t[SIM {sim_slot}] {tsv_text}\n")
  chown_user(sms_file)
  send_fifo("/tmp/dwm_plugin_sms.fifo", "REFRESH")
  run_user_cmd(
    'CONTACTNAME="$(sxmo_contacts.sh --name-or-number "$SXMO_SMS_SENDER" 2>/dev/null || printf "%s" "$SXMO_SMS_SENDER")"; '
    'sxmo_notifs.sh new -g "incoming-message-$SXMO_SMS_SENDER" "xsms tailtextlog \'$SXMO_SMS_SENDER\'" "$CONTACTNAME: $SXMO_SMS_TEXT" >/dev/null 2>&1 || true; '
    'sxmo_hook_sms.sh "$CONTACTNAME" "$SXMO_SMS_TEXT"',
    extra_env={"SXMO_SMS_SENDER": sender, "SXMO_SMS_TEXT": text}
  )

def handle_decoded_sms(info, sim_slot):
  if not info:
    return
  now = time.time()
  for k, ts in list(recent_sms_dedup.items()):
    if now - ts > 120.0:
      del recent_sms_dedup[k]
  seg_key = ("seg", info["sender"], info["time"], info["ref"], info["total"], info["seq"], info["text"])
  if seg_key in recent_sms_dedup and now - recent_sms_dedup[seg_key] < 15.0:
    return
  recent_sms_dedup[seg_key] = now
  if info["ref"] is not None and info["total"] > 1:
    done_key = ("csms_done", info["sender"], info["ref"], info["total"])
    if done_key in recent_sms_dedup:
      return
    key = (info["sender"], info["ref"], info["total"])
    parts = multipart_buf.setdefault(key, {"ts": now, "time": info["time"], "slot": sim_slot, "segs": {}})
    parts["ts"] = now
    parts["slot"] = sim_slot
    parts["segs"][info["seq"]] = info["text"]
    if len(parts["segs"]) >= info["total"]:
      full_text = _normalize_sms_text("".join(parts["segs"].get(i, "") for i in range(1, info["total"] + 1)))
      msg_time = parts.get("time") or info["time"]
      del multipart_buf[key]
      recent_sms_dedup[done_key] = now
      deliver_sms_to_sxmo(info["sender"], msg_time, full_text, sim_slot)
  else:
    deliver_sms_to_sxmo(info["sender"], info["time"], _normalize_sms_text(info["text"]), sim_slot)

def flush_stale_multipart(wms_sock=None, wms_addr=None, txn=1, sim_slot=2):
  now = time.time()
  has_expired = any(now - parts["ts"] >= 45.0 for parts in multipart_buf.values())
  if has_expired and wms_sock is not None and wms_addr is not None:
    txn = poll_stored_sms(wms_sock, wms_addr, txn, sim_slot)
    now = time.time()
  for key, parts in list(multipart_buf.items()):
    if now - parts["ts"] >= 45.0:
      sender, ref, total = key
      full_text = _normalize_sms_text("".join(parts["segs"].get(i, "") for i in range(1, total + 1)))
      del multipart_buf[key]
      recent_sms_dedup[("csms_done", sender, ref, total)] = now
      if full_text:
        deliver_sms_to_sxmo(sender, parts.get("time", ""), full_text, parts.get("slot", sim_slot))
  return txn

def poll_stored_sms(wms_sock, wms_addr, txn, sim_slot):
  for _pass in range(3):
    found_any = False
    decoded_batch = []
    for stype in (0, 1):
      # WMSListMessages (0x0031): TLV 0x01 = storage_type, TLV 0x11 = message_mode (1 = GW)
      tlvs = qmi_req(wms_sock, wms_addr, txn, 0x0031, struct.pack("<BHB", 0x01, 1, stype) + struct.pack("<BHB", 0x11, 1, 1))
      txn = (txn % 60000) + 1
      raw_list = tlvs.get(0x01, b"")
      if len(raw_list) < 4:
        continue
      cnt = struct.unpack("<I", raw_list[:4])[0]
      off = 4
      for _ in range(cnt):
        if off + 5 > len(raw_list):
          break
        idx, tag = struct.unpack("<IB", raw_list[off:off+5])
        off += 5
        # tag 0 = MT read, 1 = MT not read
        if tag in (0, 1):
          found_any = True
          r_tlvs = qmi_req(wms_sock, wms_addr, txn, 0x0022, struct.pack("<BHBI", 0x01, 5, stype, idx) + struct.pack("<BHB", 0x10, 1, 1))
          txn = (txn % 60000) + 1
          qmi_req(wms_sock, wms_addr, txn, 0x0024, struct.pack("<BHB", 0x01, 1, stype) + struct.pack("<BHI", 0x10, 4, idx) + struct.pack("<BHB", 0x12, 1, 1))
          txn = (txn % 60000) + 1
          raw_msg = r_tlvs.get(0x01, b"")
          if len(raw_msg) >= 4:
            dlen = struct.unpack("<H", raw_msg[2:4])[0]
            pdu = raw_msg[4:4+dlen]
            info = decode_sms_deliver(pdu, only_tpdu=False)
            if info:
              decoded_batch.append(info)
    for info in decoded_batch:
      handle_decoded_sms(info, sim_slot)
    if not found_any:
      break
  return txn

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",
}

active_calls = {}
audio_opened = False

def stop_ringing_user():
  run_user_cmd(
    "rm -f /tmp/sxmo_call_ringing; "
    "sxmo_jobs.sh stop ringing >/dev/null 2>&1; "
    "pkill -TERM -f sxmo_hook_ring.sh 2>/dev/null; "
    "pkill -TERM -f 'pw-play.*ring' 2>/dev/null; "
    "pkill -TERM -f 'mpv.*ring' 2>/dev/null; "
    "pkill -TERM -x sxmo_vibrate 2>/dev/null || true"
  )

def set_q6voiced_audio(enable):
  global audio_opened
  if enable and not audio_opened:
    audio_opened = True
    subprocess.run(["dbus-send", "--system", "--type=signal", "/", "org.ofono.VoiceCallManager.CallAdded"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    run_user_cmd("sxmo_modemaudio.sh setup_audio")
  elif not enable and audio_opened:
    audio_opened = False
    subprocess.run(["dbus-send", "--system", "--type=signal", "/", "org.ofono.VoiceCallManager.CallRemoved"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    run_user_cmd("sxmo_modemaudio.sh reset_audio")

def has_sub1_call_files():
  try:
    return any(fn.startswith("sub1_") for fn in os.listdir(CALLS_DIR))
  except Exception:
    return False

def has_mm_call_files():
  try:
    for fn in os.listdir(CALLS_DIR):
      if fn and fn[0].isdigit():
        return True
  except Exception:
    pass
  return False

def sync_sub1_calls(calls, sim_slot):
  global active_calls
  now_str = datetime.datetime.now().astimezone().isoformat(timespec="seconds")
  for old_cid, old_info in list(active_calls.items()):
    if old_cid not in calls:
      if old_info.get("state") == "terminated":
        del active_calls[old_cid]
      else:
        calls[old_cid] = {
          "id": old_cid,
          "state": 9,
          "dir": old_info.get("dir", 1),
          "num": old_info.get("num", ""),
        }

  for cid, c in list(calls.items()):
    st = STATE_MAP.get(c["state"], "unknown")
    if st == "setup":
      if c["dir"] == 1 and has_sub1_call_files():
        st = "dialing"
      else:
        continue

    # Skip calls that are already managed by ModemManager / sxmo_modem.sh on Primary GW
    if cid not in active_calls:
      if st == "terminated":
        continue
      if c["dir"] == 1 and not has_sub1_call_files():
        continue
      if c["dir"] == 2:
        time.sleep(0.35)
        if has_mm_call_files():
          continue

    num = c["num"] or active_calls.get(cid, {}).get("num") or "Unknown"
    if num and num != "Unknown" and not num.startswith("+") and len(num) >= 10:
      num = "+" + num
    c["num"] = num
    prev = active_calls.get(cid, {}).get("state")
    call_key = f"sub1_{cid}"

    # Update /run/user/10000/sxmo_calls/sub1_<id>.<state>
    for fn in os.listdir(CALLS_DIR):
      if fn.startswith(f"{call_key}.") and not fn.endswith(".initiatedcall") and not fn.endswith(".pickedupcall") and not fn.endswith(".mutedring"):
        try:
          os.remove(os.path.join(CALLS_DIR, fn))
        except Exception:
          pass
    if st != "terminated":
      try:
        open(os.path.join(CALLS_DIR, f"{call_key}.{st}"), "w").close()
        chown_user(os.path.join(CALLS_DIR, f"{call_key}.{st}"))
      except Exception:
        pass
    else:
      for fn in os.listdir(CALLS_DIR):
        if fn.startswith(f"{call_key}."):
          try:
            os.remove(os.path.join(CALLS_DIR, fn))
          except Exception:
            pass

    if st == prev:
      continue
    active_calls[cid] = {"state": st, "num": num, "dir": c["dir"]}

    if st == "ringing-in":
      if has_mm_call_files():
        del active_calls[cid]
        continue
      append_modemlog(f"{now_str}\tcall_ring\t{num}\t[SIM {sim_slot}]\n")
      send_fifo("/tmp/dwm_plugin_callscreen.fifo", f"INCOMING {call_key} {num} SIM{sim_slot}")
      run_user_cmd(f"sxmo_jobs.sh start --group ringing sxmo_hook_ring.sh '{num}'")
    elif st in ("dialing", "ringing-out"):
      set_q6voiced_audio(True)
      if prev not in ("dialing", "ringing-out"):
        append_modemlog(f"{now_str}\tcall_dial\t{num}\t[SIM {sim_slot}]\n")
      send_fifo("/tmp/dwm_plugin_callscreen.fifo", f"OUTGOING {call_key} {num} SIM{sim_slot}")
    elif st == "active":
      stop_ringing_user()
      set_q6voiced_audio(True)
      append_modemlog(f"{now_str}\tcall_start\t{num}\t[SIM {sim_slot}]\n")
      send_fifo("/tmp/dwm_plugin_callscreen.fifo", f"ACTIVE {call_key} {num} SIM{sim_slot}")
    elif st == "terminated":
      stop_ringing_user()
      evt = "call_missed" if prev == "ringing-in" else "call_hangup"
      append_modemlog(f"{now_str}\t{evt}\t{num}\t[SIM {sim_slot}]\n")
      send_fifo("/tmp/dwm_plugin_callscreen.fifo", "ENDED CALL ENDED")

  has_live = any(v["state"] in ("dialing", "ringing-out", "active", "held", "ringing-in", "waiting") for v in active_calls.values())
  if not has_live:
    removed_stale = False
    for fn in os.listdir(CALLS_DIR):
      if fn.startswith("sub1_"):
        try:
          os.remove(os.path.join(CALLS_DIR, fn))
          removed_stale = True
        except Exception:
          pass
    if removed_stale:
      stop_ringing_user()
      send_fifo("/tmp/dwm_plugin_callscreen.fifo", "ENDED CALL ENDED")
    if audio_opened:
      set_q6voiced_audio(False)

while True:
  wms_addr = lookup_srv(QMI_SERVICE_WMS)
  voice_addr = lookup_srv(QMI_SERVICE_VOICE)
  uim_addr = lookup_srv(QMI_SERVICE_UIM)
  if not (wms_addr and voice_addr):
    time.sleep(3)
    continue

  sec_slot = 2
  if uim_addr:
    us = socket.socket(AF_QIPCRTR, socket.SOCK_DGRAM)
    ut = qmi_req(us, uim_addr, 1, 0x002F)
    us.close()
    st_val = ut.get(0x10, b"")
    if len(st_val) >= 8:
      _, _, sec_gw_idx, _ = struct.unpack("<HHHH", st_val[:8])
      if sec_gw_idx != 0xFFFF:
        sec_slot = ((sec_gw_idx >> 8) & 0xFF) + 1

  ws = socket.socket(AF_QIPCRTR, socket.SOCK_DGRAM)
  vs = socket.socket(AF_QIPCRTR, socket.SOCK_DGRAM)
  w_txn = 1
  v_txn = 1

  # Bind both sockets to Secondary GW (sub = 1)
  qmi_req(ws, wms_addr, w_txn, 0x004C, struct.pack("<BHB", 0x01, 1, 1))
  w_txn += 1
  qmi_req(ws, wms_addr, w_txn, 0x0001, struct.pack("<BHB", 0x10, 1, 1))
  w_txn += 1
  # Configure WMS routes on Secondary GW (sub = 1) to match ModemManager:
  # Class 0 -> UIM + TRANSFER_AND_ACK (0x03), Class 1/2/3/None -> UIM + STORE_AND_NOTIFY (0x01)
  # so the baseband sends 3GPP RP-ACK in hardware for every multipart segment immediately.
  route_list = bytes.fromhex("060000000003000100010002000100030001000400010005ff02")
  route_tlvs = struct.pack("<BH", 0x01, len(route_list)) + route_list + struct.pack("<BHB", 0x10, 1, 0)
  qmi_req(ws, wms_addr, w_txn, 0x0032, route_tlvs)
  w_txn += 1

  qmi_req(vs, voice_addr, v_txn, 0x0044, struct.pack("<BHB", 0x01, 1, 1))
  v_txn += 1
  # Register for Voice Call Notification Events (TLV 0x13 = 1)
  qmi_req(vs, voice_addr, v_txn, 0x0003, struct.pack("<BHB", 0x13, 1, 1))
  v_txn += 1

  w_txn = poll_stored_sms(ws, wms_addr, w_txn, sec_slot)
  last_poll = time.time()

  try:
    while True:
      if pending_inds:
        poll_timeout = 0.0
      elif active_calls or has_sub1_call_files():
        poll_timeout = 1.0
      elif multipart_buf:
        poll_timeout = 2.0
      elif os.path.exists("/tmp/bananarchy_screen_locked"):
        poll_timeout = None
      else:
        poll_timeout = 600.0
      r, _, _ = select.select([ws, vs], [], [], poll_timeout)
      got_voice_ind = False
      events = []
      while pending_inds:
        events.append(pending_inds.pop(0))
      for sock in r:
        pkt, _ = sock.recvfrom(4096)
        events.append((sock, pkt))
      for sock, pkt in events:
        if len(pkt) < 7:
          continue
        flags, txn, mid, _ = struct.unpack("<BHHH", pkt[:7])
        if flags != 0x04:
          continue
        tlvs = parse_tlvs(pkt)
        if sock is ws and mid == 0x0001:
          # WMSEventReport indication
          if 0x11 in tlvs and len(tlvs[0x11]) >= 8:
            # Transfer-route MT message: [ack_ind(1), txn_id(4), format(1), len(2), data...]
            tr = tlvs[0x11]
            ack_ind = tr[0]
            mt_txn_id = struct.unpack("<I", tr[1:5])[0]
            dlen = struct.unpack("<H", tr[6:8])[0]
            pdu = tr[8:8+dlen]
            if ack_ind == 0:
              # Send QMI_WMS_SEND_ACK (0x0026): TLV 0x01 = [txn_id(4), protocol=1(GW), success=1], TLV 0x10 = 3GPP RP-ACK
              ack_tlvs = (
                struct.pack("<BHIBB", 0x01, 6, mt_txn_id, 1, 1)
                + struct.pack("<BHBH", 0x10, 5, 0x00, 2)
                + b"\x00\x00"
              )
              qmi_req(ws, wms_addr, w_txn, 0x0026, ack_tlvs)
              w_txn = (w_txn % 60000) + 1
            info = decode_sms_deliver(pdu, only_tpdu=True)
            if info:
              handle_decoded_sms(info, sec_slot)
          if 0x10 in tlvs:
            w_txn = poll_stored_sms(ws, wms_addr, w_txn, sec_slot)
        elif sock is vs and mid == 0x002E:
          # VoiceAllCallStatusIndication
          got_voice_ind = True
          calls = parse_call_info(tlvs)
          if not any(c["num"] for c in calls.values()):
            full_tlvs = qmi_req(vs, voice_addr, v_txn, 0x002F)
            v_txn = (v_txn % 60000) + 1
            full_calls = parse_call_info(full_tlvs)
            for cid, fc in full_calls.items():
              if cid in calls and fc["num"]:
                calls[cid]["num"] = fc["num"]
          sync_sub1_calls(calls, sec_slot)

      if multipart_buf:
        w_txn = poll_stored_sms(ws, wms_addr, w_txn, sec_slot)
        w_txn = flush_stale_multipart(ws, wms_addr, w_txn, sec_slot)

      if not got_voice_ind and (active_calls or has_sub1_call_files()):
        full_tlvs = qmi_req(vs, voice_addr, v_txn, 0x002F)
        v_txn = (v_txn % 60000) + 1
        sync_sub1_calls(parse_call_info(full_tlvs), sec_slot)

      if not os.path.exists("/tmp/bananarchy_screen_locked") and time.time() - last_poll >= 600.0:
        w_txn = poll_stored_sms(ws, wms_addr, w_txn, sec_slot)
        last_poll = time.time()
  except Exception:
    pass
  finally:
    ws.close()
    vs.close()
  time.sleep(2)
PY
    ;;

  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
    ;;

  *)
    echo "Usage: $0 [boot|status|switch <1|2>|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
