#!/bin/bash
# Turn on globalstar satellite radio, start its ppp daemon
radio=globalstar
# Get power port and serial port from configuration
powerSerial=`python /home/hotspot/smc-script/modemConfig.py $MODEM_CONFIG_FILE $radio`
if [ $? != 0 ]; then
   echo $powerSerial
   echo Could not get configuration for $radio radio
   exit 1
fi

# Get power port
powerPort=`echo $powerSerial | awk '{print $1}'`

# Get serial port
serialPort=`echo $powerSerial | awk '{print $2}'`

echo Turn on power port $powerPort
/home/smc/bin/SetPowerSwitch $powerPort 1

echo Wait for modem initialization
sleep 9

# These are the dialing/login parameters. Change as needed.
TELEPHONE='#777'      # The telephone number for the connection
ACCOUNT=          # The account name for logon (as in 'George Burns')
PASSWORD=         # The password for this account (and 'Gracie Allen')
LOCAL_IP=        # Local IP address if known. Dynamic = 0.0.0.0
REMOTE_IP=       # Remote IP address if desired. Normally 0.0.0.0
NETMASK=255.255.255.0   # The proper netmask if needed

#
# Export them so that they will be available to dialing script
export TELEPHONE ACCOUNT PASSWORD
#
# This is the location of the script which dials the phone and logs
# in.  Please use the absolute file name as the $PATH variable is not
# used on the connect option.  (To do so on a 'root' account would be
# a security hole so don't ask.)
#
DIALER_SCRIPT=/tmp/dialer-script.txt

cat <<EOF > $DIALER_SCRIPT

#!/bin/bash
#
# Dial the Globalstar gateway#
/usr/sbin/chat -v                                        \
        TIMEOUT         15                               \
        ABORT           '\nBUSY\r'                      \
        ABORT           '\nNO ANSWER\r'                 \
        ABORT           '\nRINGING\r\n\r\nRINGING\r'    \
        ''              AT                            \
        TIMEOUT         60                              \
        OK              ATDT$TELEPHONE                  \
        CONNECT         ''                              \

EOF



#
#
chmod a+x $DIALER_SCRIPT

echo Initiate connection and run ppp on the serial port
/usr/sbin/pppd debug defaultroute /dev/ttyLX0 19200 \
        $LOCAL_IP:$REMOTE_IP noauth \
        connect $DIALER_SCRIPT

# Test connection to internet try to ping google.com
success=false
for i in {1..30}
do
  echo Try \#$i to ping google.com
  ping -c 3 google.com
  if [ $? -eq 0 ]; then
    echo Able to ping google.com
    success=true
    break
  fi
  sleep 5
done

if ! $success; then
  echo Cannot ping google.com - no internet connection?
  exit 1
fi

echo Get public IP address and email it to shore
ipaddr=`wget -qO- http://ipecho.net/plain ; echo`
echo public IP address: $ipaddr
/home/hotspot/smc-script/pymail.py 'hotspot-noreply' 'globalstarOn: SMC connected to internet' $ipaddr 'oreilly@mbari.org chma@mbari.org bkieft@mbari.org'

echo synchronize clock with NTP
ntpdate -u 0.in.pool.ntp.org

