#!/sbin/openrc-run

name="Modem WWAN port"
description="Activate the WWAN port on the embedded QMI modem"

depend() {
  need rmtfs
  before ofono
  before modemmanager
}

start() {
  ebegin "Activating Modem WWAN port"
  if ! [ -x "$(command -v qmicli)" ]; then
    eend 0
    return 0
  fi

  QMICLI_MODEM=""
  count=0
  while [ -z "$QMICLI_MODEM" ] && [ "$count" -lt 12 ]; do
    if timeout 3 qmicli --silent -pd qrtr://0 --uim-noop >/dev/null 2>&1; then
      QMICLI_MODEM="timeout 4 qmicli --silent -pd qrtr://0"
      break
    fi
    sleep 1
    count=$((count + 1))
  done

  if [ -n "$QMICLI_MODEM" ]; then
    $QMICLI_MODEM --dpm-open-port=hw-data-ep-type=bam-dmux,hw-data-ep-iface-number=1,hw-data-rx-id=1,hw-data-tx-id=1 >/dev/null 2>&1 || true
  fi

  for f in /etc/NetworkManager/system-connections/*.nmconnection; do
    [ -f "$f" ] || continue
    if grep -q "^type=gsm" "$f" 2>/dev/null; then
      sed -i '/^\[ipv6\]/,/^\[/ s/^method=auto$/method=ignore/' "$f" 2>/dev/null || true
    fi
  done
  eend 0
}
