#!/bin/bash
#
# ifplugd daemon script for Arch Linux

. /etc/rc.conf
. /etc/rc.d/functions

shopt -s extglob

# env vars
daemonname=ifplugd
cfg=/etc/ifplugd/ifplugd.conf
PID=$(pidof -o %PPID ifplugd)

# source configuration file
[[ -r $cfg ]] && . "$cfg"

# discover interfaces to monitor
# (replacing INTERFACES with NET_IFS, since AL
# already uses it in /etc/rc.conf)
if [[ $NET_IFS ]]; then
  net_ifs=($NET_IFS)
else
  net_ifs=(/sys/class/net/!(lo))
  net_ifs=("${net_ifs[@]##*/}")
fi

case $1 in
  start)
    stat_busy "Starting $daemonname: ${net_ifs[*]}"

    for nic in "${net_ifs[@]}"; do
      # only start if a PID doesn't already exist
      if [[ ! -f /var/run/ifplugd.$nic.pid ]]; then
        args=ARGS_$nic
        [[ -z ${!args} ]] && args=$ARGS || args=${!args}
        ifplugd -i "$nic" $args

        # use presence of PID file to check for start success
        [[ -f /var/run/ifplugd.$nic.pid ]] || (( ++err ))
      fi
    done
    unset nic

    if (( err )); then
      stat_fail
      exit 1
    else
      add_daemon $daemonname
      stat_done
    fi
    ;;
  stop)
    stat_busy "Stopping $daemonname: ${net_ifs[*]}"

    for nic in /var/run/ifplugd.*.pid; do
      [[ -f $nic ]] || { (( ++err )); break; }
      nic=${nic%.pid}
      nic=${nic##*.}
      ifplugd -k -i "$nic" || (( ++err ))
    done

    if (( err )); then
      stat_fail
      exit 1
    else
      rm_daemon $daemonname
      stat_done
    fi
    ;;
  restart)
    $0 stop
    sleep 1
    $0 start
    ;;
  status)
    for nic in "${net_ifs[@]}"; do
      ifplugd -c -i "$nic"
    done
    unset nic
    ;;
  suspend)
    stat_busy "Suspending $daemonname: ${net_ifs[*]}"
    for nic in "${net_ifs[@]}"; do
      ifplugd -S -i $nic || (( ++err ))
    done
    unset nic

    if (( err )); then
      stat_fail
      exit 1
    else
      stat_done
    fi
    ;;
  resume)
    stat_busy "Resuming $daemonname ${net_ifs[*]}"

    for nic in "${net_ifs[@]}"; do
      ifplugd -R -i $nic || (( ++err ))
    done
    unset nic

    if (( err )); then
      stat_fail
      exit 1
    else
      stat_done
    fi
    ;;
  *)
    echo "usage: $0 {start|stop|restart|status|suspend|resume}"
esac
exit 0
