#!/bin/sh

atcmd_usage() 
{
	[ $# -gt 0 ] && echo "atcmd: $*"
	echo "
usage: atcmd [options...] <cmd>

Options:
	-s  use the second modem
" >&2
	exit 1
}

MSERVICE="modemd"
MINDEX="modem"
IPC_NAME_ATCMD="rmsg_atcmd_$$"

# Parse options
while [ $# -gt 0 ]; do
	arg="$1"
	case $arg in
	-s)		
		MSERVICE="modemd2"
		MINDEX="modem2"		
		;;
	-*)
		atcmd_usage "unknown option $arg"
		;;
	*)
		break
		;;
	esac
	shift
done

[ $# -lt 1 ] && atcmd_usage "cmd not specified "

RESULT=`renv get ${MINDEX}_ready 2>/dev/null`
if [ ${RESULT:-false} == false ]; then
    echo "failed to send AT, modem is initializing" >&2
    exit 1
fi

RESULT=`rmsg -p -n ${IPC_NAME_ATCMD} -t 180 ${MSERVICE} cmd at command $1 timeout 180 2>/dev/null`
RETVAL=$?
if [ ${RETVAL} == 0 ]; then
    echo "${RESULT}"
else
    echo ERROR >&2
fi
exit ${RETVAL}