#!/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

device=eth0 #default interface
gateway=""
DNS="yes"
mode="dhcp"
#wirma default values for static ip address
address=192.168.4.155
netmask=255.255.255.0
broadcast=192.168.4.255


readconf()
{
    if [ -f /tmp/conf.$device ]; then
    . /tmp/conf.$device
    fi

    if [ -n "$nameserver1" ]; then
    echo "nameserver " > /tmp/resolv.conf.$device
    echo $nameserver1 >> /tmp/resolv.conf.$device
    echo $nameserver2 >> /tmp/resolv.conf.$device
    DNS="yes"
    mode="static"
    fi
}

addRoute()
{
  # delete default route
    /sbin/route del default 1>/dev/null 2>/dev/null

    if [ -f /tmp/gateway.$device ]; then
    #file created by udhcpc script
    . /tmp/gateway.$device
    fi

    if [ -n "${gateway}" ]; then
    GATEWAY=${gateway}
    fi

    /sbin/route add default dev ${device} gw ${GATEWAY} 1>/dev/null 2>/dev/null
}

addResolv()
{
    if [ "${DNS}" = "yes" ]; then
    if [ -f /tmp/resolv.conf.$device ]; then
        cp /tmp/resolv.conf.$device /etc/resolv.conf 1>/dev/null 2>/dev/null
    fi
    fi
}

startEthernet ()
{
    if [ "${mode}" = "dhcp" ]; then
    /sbin/udhcpc -n -q -i ${device} -s /etc/udhcpc.sh 1>/dev/null 2>/dev/null
    if [ -f /tmp/udhcpc.ok ]; then
        return;
    else
        exit 1
    fi
    else
    /sbin/ifconfig ${device} ${address} broadcast ${broadcast} netmask ${netmask} 1>/dev/null 2>/dev/null
    fi
}


case "$1" in

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

    for arg in $@; do
        if [ "$arg" != "$1" ]; then
        echo $arg >> /tmp/conf.$device;
        fi
    done

    echo $device
        exit 0
    ;;
    start)
    if [ -z "$2" ]; then
        exit 1
    fi
    device=$1
    readconf
        startEthernet
    addRoute
        addResolv
    exit 0
        ;;

    stop)
    if [ -z "$2" ]; then
        exit 1
    fi
        /sbin/ifconfig ${device} down 1>/dev/null 2>/dev/null
    exit 0
        ;;

    *)
        exit 1
        ;;
esac
