#!/bin/sh
set -eu
QMICLI_MODEM=

if command -v systemd-notify > /dev/null; then
	trap '[ $? -eq 0 ] && systemd-notify --ready' EXIT
fi

# libqmi must be present to use this script.
if ! [ -x "$(command -v qmicli)" ]
then
	echo 'qmicli is not installed.'
	exit 1
fi

# Prepare a qmicli command with desired modem path.
# The modem may appear after some delay, wait for it.
count=0
while [ -z "$QMICLI_MODEM" ] && [ "$count" -lt "45" ]
do
	# Check if QRTR is available
	if qmicli --silent -pd qrtr://0 --uim-noop > /dev/null
	then
		QMICLI_MODEM="qmicli --silent -pd qrtr://0"
		echo "Using qrtr://0"
	fi
	sleep 1
	count=$((count+1))
done
echo "Waited $count seconds for modem device to appear"

if [ -z "$QMICLI_MODEM" ]
then
	echo 'No modem available.'
	exit 2
fi

$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
exit $?
