#!/bin/sh

DEBUG_NETWORK_FLAG="/var/tvip/log/debug_network"
DEBUG_NETWORK_FILE="/tmp/network.log"
PPPD_FLAG="/var/tvip/ppp/enable."

IFACE=$1

# States :
# in A cable was plugged in, or carrier came up. The command should bring the interface up. The command is run asynchronously, and it should exit with status 0 on success.
# out A cable was plugged out, or carrier went down. The command should bring the interface down. The command is run asynchronously, and it should exit with status 0 on success.
# probe The command should load and initialise the driver for this interface, if possible, and bring the interface into the "up" state, so that it can generate netlink(7) events. The command is run synchronously; it must exit with status code 0 if it succeeds, otherwise with a non-zero exit code or signal.
STATE=$2

log() {
  echo "NETPLUG: $@"
  if [ -f ${DEBUG_NETWORK_FLAG} ]; then
    echo `date` "NETPLUG: $@" >> ${DEBUG_NETWORK_FILE}
  fi
}

export RUN_UNDER_NETPLUG="yes"

log "Interface ${IFACE} changed state to ${STATE}"


case "${STATE}" in
  in)
    #log "Bringing up ${IFACE}"
    #ifconfig ${IFACE} up
    log "Restarting network for interface ${IFACE}, reason: ${STATE}"
    export INTERFACES_LIST=${IFACE}
    /etc/init.d/network restart
    if [ -f ${PPPD_FLAG}${IFACE} ]; then
      log "Starting pppd for ${IFACE}"
      /usr/sbin/pppd ${IFACE}
    fi
    ;;
    
  out)
    if [ -f ${PPPD_FLAG}${IFACE} ]; then
      log "Stopping pppd for ${IFACE}"
      killall pppd
    fi
    log "Restarting network for interface ${IFACE}, reason: ${STATE}"
    export INTERFACES_LIST=${IFACE}
    /etc/init.d/network restart
    ;;
    
  probe)
    ;;
  *)
    ;;
esac
