#!/bin/sh

#*******************************************************************************
# Copyright (c) 2012 Sierra Wireless and others.
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
#     Sierra Wireless - initial API and implementation
#*******************************************************************************

#old script not updated to fit last API definition to be used in linux/Bearer.lua

PPPD=pppd
CHAT=chat
modemport=/dev/ttyS2
PPPDDEVICE=ppp0

apn=""

CHATSTART=/tmp/chatstart
CHATSTOP=/tmp/chatstop



buildChatScript()
{
    echo "'' 'AT'" >${CHATSTART}
    echo "'OK' '\dAT+CGDCONT=1,\"IP\",\"${apn}\"'" >>${CHATSTART}
    echo "'OK' 'ATE0V1'" >>${CHATSTART}
    echo "'OK' 'ATDT*99***1#'" >>${CHATSTART}
    echo "'CONNECT'" >>${CHATSTART}
    echo >>${CHATSTART}

    echo "'' '+++ATH'" >${CHATSTOP}
    echo "'NO CARRIER' ''" >>${CHATSTOP}
    echo "'' 'AT'" >>${CHATSTOP}
    echo >>${CHATSTOP}
}

startPPP()
{
    #set serial speed to 115200 and active raw mode
    stty -F ${modemport} raw speed 115200 1>/dev/null 2>/dev/null

    if [ -z "${IFSTART}" ]; then
    ${PPPD} ${modemport} 115200 modem debug novj usepeerdns lock refuse-chap updetach connect ${CHAT}' -t 15 -v -f '$CHATSTART disconnect ${CHAT}' -t 15 -v -f '$CHATSTOP 1>/dev/null 2>/dev/null
    fi
    PPPSTATUS=$?

    #verifying if interface is mounted or not
    IFUP=`/sbin/route -n | /bin/grep ${PPPDDEVICE} 2>/dev/null`

    if [ "$PPPSTATUS" -eq "0" ] && [ -n "${IFUP}" ] && [ -f /etc/ppp/resolv.conf ]; then #interface mount, return
    return
    fi

    exit 1
}

case "$1" in

    init)
    if [ -f /tmp/conf.ppp ]; then
        rm /tmp/conf.ppp 1>/dev/null 2>/dev/null
    fi

    for arg in $@; do
        if [ "$arg" != "$1" ]; then
        eval $arg;
        echo $arg >> /tmp/conf.ppp;
        fi
    done
    buildChatScript
    echo $PPPDDEVICE
        exit 0
    ;;
    start)
    if [ -z "$2" ]; then
        exit 1
    fi
    if [ -f /tmp/conf.ppp ]; then
        . /tmp/conf.ppp
    fi

    startPPP
    sleep 2
    exit 0
        ;;

    stop)
    if [ -z "$2" ]; then
        exit 1
    fi
        killall `basename ${PPPD}`
    sleep 5
    exit 0
        ;;

    *)
        exit 1
        ;;
esac
