#!/bin/sh

# Modem initialisation script for comms module
# Author: dylan@kses.net
# 2014-11-11

MODEM=/dev/ttyUSB2
MODEM_LOG=/var/log/simcom.log
GNXIO=/usr/bin/gnxio
GNXID=/usr/bin/gnxid

GPS_ON=/tmp/gpson
# Reset modem clear out this as well
if [ -f $GPS_ON ]; then
    rm -f $GPS_ON
fi

function error()
{
    echo "$1" >&2
}

if [[ ! -x "${GNXIO}" ]] ; then
    error "${GNXIO} is missing or not executable"
    exit 1
fi

if [[ ! -x "${GNXID}" ]] ; then
    error "${GNXID} is missing or not executable"
    exit 1
else
    ID=`${GNXID}`
    if [[ "${ID}" != 7 ]] ; then
        error "This is not a KSES comms module"
        exit 1
    fi
fi

function gnxio_toggle()
{
    PIN=$1
    STATE=$2
    echo -n "[${PIN} -> ${STATE}] ... "
    ${GNXIO} set ${PIN} ${STATE}
    RESULT=`gnxio get ${PIN}`
    if [[ "${RESULT}" == "${STATE}" ]] ; then
        echo "OK"
    else
       echo "failed"
       error "Error toggling pin ${PIN}"
       exit 1
    fi
}

function modem_tx()
{
    if [[ -c ${MODEM} ]] ; then
        echo -e "$1\r" >> "${MODEM}"
        echo "TX: $1" >> "${MODEM_LOG}"
    else
        error "${MODEM} is not a character device"
        exit 1
    fi
}

function modem_rx()
{
    IFS=$'\r\n' :; RX=($(timeout 0.75 cat ${MODEM}))
    for line in "${RX[@]}" ;
    do
        echo "RX: ${line}" >> ${MODEM_LOG}
        if [[ "${line}" == "OK" ]] ; then
            RX_RESULT="OK"
        fi
    done
}

function modem_txrx()
{
    modem_tx "$1"
    RX_RESULT="failed"
    modem_rx
}

echo "Begin modem initialisation"
date "+%Y-%m-%d %T" >> "${MODEM_LOG}"
PWR=`${GNXIO} get GSM_OFF`

if [[ "${PWR}" == "low" ]] ; then
    echo -n "Modem power OFF "
    gnxio_toggle GSM_OFF high
    sleep 2
fi

echo -n "Modem power ON "
gnxio_toggle "GSM_OFF" "low"

echo -n "Ignition start "
gnxio_toggle GSM_IGT high
sleep 1
echo -n "Ignition release "
gnxio_toggle GSM_IGT low

echo -n "Waiting for ${MODEM} ."
while [[ ! -c "${MODEM}" ]] ; do
    sleep 1
    echo -n "."
done
echo " OK"

modem_rx 

MODEM_CMD="ATZ"
echo -n "Modem reset (${MODEM_CMD}) ... "
modem_txrx "${MODEM_CMD}"
echo "${RX_RESULT}"
if [[ ${RX_RESULT} != "OK" ]] ; then
    error "No reply to ${MODEM_CMD} from modem"
    exit 1
fi

MODEM_CMD="AT+CGPS=1"
echo -n "Activate GPS (${MODEM_CMD}) ... "
modem_txrx "${MODEM_CMD}"
echo "${RX_RESULT}"
if [[ ${RX_RESULT} != "OK" ]] ; then
    error "Could not activate GPS"
    exit 1
fi

MODEM_CMD="AT+IPR=4000000"
echo -n "Set baud to maximum (${MODEM_CMD}) ... "
modem_txrx "${MODEM_CMD}"
echo "${RX_RESULT}"
if [[ ${RX_RESULT} != "OK" ]] ; then
    error "Could not set baudrate"
    exit 1
fi

exit 0
