#!/bin/sh

# Read config file if it is present.
if [ -r "$1" ]; then
    . $1
else
    echo "SERIALIF: exit: no config"
    exit 1
fi

if [ -e "/var/run/ppp$SERIALIF_UNIT.pid" ]; then
    echo "SERIALIF: killing old instance of pppd"
    pid=`cat "/var/run/ppp$SERIALIF_UNIT.pid"`
    kill -9 $pid
fi

if [ "$DEFAULT_ROUTE" = "yes" ]; then
    /usr/local/bin/serialif/renameif "ppp$SERIALIF_UNIT" "serial$IF_NUMBER" "$SERIALIF_REMOTE_IP" &> /dev/null &
else
    /usr/local/bin/serialif/renameif "ppp$SERIALIF_UNIT" "serial$IF_NUMBER" &> /dev/null &
fi

while true; do
    DEV=`cat /usr/local/etc/telem/hw-run.xml | grep "Port index=\"$PORT_TTY\"" | awk '{ print $5 }' | cut -f2 -d"\""`
    FINDER=`cat /usr/local/etc/telem/hw-run.xml | grep "Port index=\"$PORT_TTY\"" | awk '{ print $4 }' | cut -f2 -d"\""`
    
    if [ "$FINDER" = "FixedSerialPortFinder" ]; then
        SERIALIF_TTY=$DEV
    else
        SERIALIF_TTY=`ls $DEV | grep "tty"`
    fi
    
    echo "unit $SERIALIF_UNIT" > "/tmp/options_s$SERIALIF_UNIT"
    echo "ipparam \"SERIALIF\"" >> "/tmp/options_s$SERIALIF_UNIT"
    
    pppd "$SERIALIF_TTY" "$SERIALIF_BAUDRATE" file "/tmp/options_s$SERIALIF_UNIT" "$SERIALIF_LOCAL_IP:$SERIALIF_REMOTE_IP" mru "$MRU" mtu "$MTU"
    
    rm -f "/tmp/options_s$SERIALIF_UNIT"
    
    echo "SERIALIF: exit"
    sleep 2
done