#!/bin/sh

# /etc/init.d/udhcpc: start or stop udhcpc client

source /etc/utils/shell-utils.sh
DEBUG=1

start_dhcp()
{
    start-stop-daemon --start --quiet -p $PID_FILE --exec $DAEMONFULL -- -p $PID_FILE -i $par_if --script /etc/udhcpc/default.script -R -b -t 10 -T 1 -A 10 -V $VENDOR -x hostname:${HOST_NAME_OPT} 1>/dev/null 2>/dev/null
    if [ "$?" == "0" ]; then
        echo "OK"
    else
        echo "already running"
    fi
}

echo "Executing >>> $0 <<<"; echo

export vendorspecinf=mcip_img,10,ip:mcport_img,11,u16:mcip_mng,12,ip:mcport_mng,13,u16:ip_log,14,ip:port_log,15,u16:portal_dhcp,22,string:tzone,23,string:upd_url,24,string:upd_sboot,25,string:upd_ver,26,string:upd_mode,27,string:upd_sb_ver,28,string:nc_ip,30,ip:nc_port,31,u16:syslog_srv,32,string:nc_level,33,u16

PATH=/bin:/usr/bin:/sbin:/usr/sbin
DAEMON=udhcpc
DAEMONFULL=/sbin/udhcpc
LOCK_ISACTIVE_FILE=/ram/lock/wifi-isactive.lock
WIFI_DRIVER_MODULE_NAME="ralink"

if [ ! -x $DAEMONFULL ]; then
    exit 0
fi

if [ "$2" == "" ]; then
  par_if=eth0
else
  par_if=$2
fi

if [ "$par_if" == "eth0" ]; then
  MAC=`$RDIR_APP MACAddress`
else
  MAC=`ifconfig wlan0 | awk '{ if ($1 == "ra0")print $5 }'`
fi

PID_FILE="/ram/run/udhcp_$par_if"

VENDOR="Infomir"`$RDIR_APP Model`
HOST_NAME_OPT="$(hostname)"

log "($1) MAC: ${MAC} VENDOR: '${VENDOR}' HOST NAME: '${HOST_NAME_OPT}'"

case "$1" in
  start)
    echo -n "Starting DHCP client for interface '$par_if': vendor = $VENDOR ..."
    start_dhcp &
    sleep 1
  ;;

  restart)
    /etc/init.d/udhcpcd stop $par_if
    /etc/init.d/udhcpcd start $par_if
  ;;

  reload)
  ;;

  force-reload)
  ;;

  stop)
    echo "Stopping DHCP client for interface '$par_if'"
    log "Stopping DHCP client for interface '$par_if'"

    #sleep 1

    start-stop-daemon --stop --quiet -p $PID_FILE || echo " not running"

    [ -x /etc/init.d/ntp-server ] && /etc/init.d/ntp-server stop

    echo "DONE"
    log "DONE"
  ;;

  renew)
        log "virtual renew"

    #start-stop-daemon --signal USR1 --stop --quiet --name $DAEMON -p $PID_FILE -- -i $par_if || echo -n " not running"
  ;;

  release)
    log "virtual release"

    #start-stop-daemon --signal USR2 --stop --quiet --name $DAEMON -p $PID_FILE -- -i $par_if || echo -n " not running"
  ;;

  *)
    echo "Usage: /etc/init.d/udhcpc {start|stop|restart|reload|force-reload}"
    exit 1
    ;;
esac

exit 0
