#!/bin/sh
#Barry Kauler LGPL 2007
#called from /usr/sbin/modemtest
#the idea is to probe modem and determine a suitable hayes command init string.

[ ! -e /dev/modem ] && exit

modem_stats_func() {
 #modem-stats has a serious bug, if return string not 'OK' then it never terminates.
 local CNTLP=1
 rm -f /tmp/modemstatsret
 modem-stats $@ >/tmp/modemstatsret &
 MPID=$!
 while [ 1 ];do
  sleep 1
  [ "`grep '^[A-Z].*' /tmp/modemstatsret`" != "" ] && break
  [ $CNTLP -gt 5 ] && break
  CNTLP=`expr $CNTLP + 1`
 done
 #may need a bit more time to receive all returns from modem...
 [ "`grep -E '^OK|^ERROR' /tmp/modemstatsret`" = "" ] && sleep 1
 kill $MPID > /dev/null 2>&1
 cat /tmp/modemstatsret
}

[ "`modem_stats_func -c 'ATZ' /dev/modem | grep '^OK$'`" = "" ] && exit

ALLSTR=""
for ONESTEP in 'Q0V1E1' 'Z' 'S0=0' '&C1' '&D2' 'S11=55' '+FCLASS=0'
do
 if [ "`modem_stats_func -c "AT$ONESTEP" /dev/modem | grep '^OK$'`" = "" ];then
  modem_stats_func -c 'ATZ' /dev/modem #maybe wise to reset modem.
  continue
 fi
 [ "$ONESTEP" = "Z" ] && continue
 ALLSTR="$ALLSTR$ONESTEP"
done

#NO, the problem with country codes is there does not seem to be one standard.
#the codes differ, also Hayes command for querying the current code differs,
#also some modems are hardwired for a particular country and will not accept
#any country code.
##country code...
SETCOUNTRY=""
#if [ -f /etc/countryinfo ];then
# . /etc/countryinfo
# if [ "`modem_stats_func -c 'ATI7' /dev/modem | grep 'Country'`" != "" ];then
#  ATCODE="AT+GCI=${MODEM_COUNTRY_CODE}"
#  [ "`modem_stats_func -c "$ATCODE" /dev/modem | grep '^OK$'`" != "" ] && SETCOUNTRY="+GC1=${MODEM_COUNTRY_CODE}"
# fi
# modem_stats_func -c 'ATZ' /dev/modem #maybe wise to reset modem.
#fi

#But, some firmware scripts in /etc/init.d/ do write a country string to
#/etc/countryinfo...
if [ -f /etc/countryinfo ];then
 . /etc/countryinfo
 if [ "$MODEM_COUNTRY_STRING" ];then
  SETCOUNTRY="`echo -n "$MODEM_COUNTRY_STRING" | sed -e 's/^AT/ /'`"
 fi
fi

echo -n "AT$ALLSTR$SETCOUNTRY" > /tmp/mymodeminitstring

###END###
