#!/bin/sh

# Bash modem dialler
# Author: dylan@kses.net
# 2014-11-13

apn=`cat /etc/ppp/apn`
pin=`cat /etc/ppp/pin`
step=0
tx_list=("ATH" "AT+CPIN?" "AT+CPIN=${pin}" "AT+CGDCONT=1,\"IP\",\"${apn}\"" "ATDT*99#")

function log()
{
   /bin/echo "${1}" >> /var/log/modem.log
}

function tx()
{
    /bin/echo -e "${1}\r"
    log "TX: ${1}"
}

function do_tx()
{
    tx "${tx_list[${step}]}"
}

function next_step()
{
    step=$((step+1))
    if [[ "${step}" -eq "${#tx_list[@]}" ]] ; then
        log "All steps succeeded"
        exit 0
    else
        /bin/sleep 1
        do_tx
    fi
}

function handle_reply()
{
    case ${step} in
        1)
            if [[ "${reply}" == "+CPIN: READY" ]] ; then
                step=$((step+1))
###             next_step
            elif [[ "${reply}" == "+CPIN: SIM PIN" ]] ; then
                next_step
            fi
        ;;
        4)
            if [[ "${reply}" =~ "CONNECT" ]] ; then
                next_step
            fi
        ;;
        *)
            if [[ "${reply}" == "OK" ]] ; then
                next_step
            fi
        ;;
    esac
}

log "Started `date +"%Y-%m-%d %T"` by parent ${PPID}"
tx "+++"
/bin/sleep 1
read -t 0
do_tx
while IFS=$'\r' read -r -t 5 reply;
do
    log "RX: ${reply}"
    if [[ "${reply}" == "ERROR" ]] ; then
        log "Failed at step ${step}"
        exit 1
    else
        handle_reply
    fi
done

log "Timed out at step ${step}"
exit 1
