#!/bin/bash
# Begin services/wpa

# Origianlly based upon lfs-bootscripts-1.12 $NETWORK_DEVICES/if{down,up}
# Written by Armin K. <krejzi at email dot com>

# Call with: IFCONFIG=<filename> /lib/services/wpa <IFACE> <up | down>

#$LastChangedBy: krejzi $
#$Date: 2013-02-04 03:21:36 +0000 (Mon, 04 Feb 2013) $

. /lib/lsb/init-functions
. $IFCONFIG

case "$2" in
   up)

      if [ -e /run/wpa_supplicant/$1.pid ]; then
         log_warning_msg "\n wpa_supplicant already running on $1."
         exit 0
      fi

      if [ ! -e /etc/sysconfig/wpa_supplicant-$1.conf ]; then
        log_info_msg "\n wpa_supplicant configuration file not present"
        log_failure_msg2
        exit 1
      fi

      log_info_msg "\n Starting wpa_supplicant on the $1 interface..."

      mkdir -p /run/wpa_supplicant

      /sbin/wpa_supplicant -q -B -Dnl80211,wext -P/run/wpa_supplicant/$1.pid -C/run/wpa_supplicant -c/etc/sysconfig/wpa_supplicant-$1.conf -i$1 ${WPA_ARGS}

      if [ "$?" != "0" ]; then
        log_failure_msg2
        exit 1
      fi

      log_success_msg2

      if [ -n "${WPA_SERVICE}" ]; then
         if [ ! -e /lib/services/${WPA_SERVICE} -a ! -x /lib/services/${WPA_SERVICE} ]; then
            log_info_msg "\n Cannot start ${WPA_SERVICE} on $1"
            log_failure_msg2
            exit 1
         fi

         IFCONFIG=${IFCONFIG} /lib/services/${WPA_SERVICE} $1 up
      fi
   ;;

   down)
      if [ -n "${WPA_SERVICE}" ]; then
         if [ ! -e /lib/services/${WPA_SERVICE} -a ! -x /lib/services/${WPA_SERVICE} ]; then
            log_warning_msg "\n Cannot stop ${WPA_SERVICE} on $1"
         else
            IFCONFIG=${IFCONFIG} /lib/services/${WPA_SERVICE} $1 down
         fi
      fi

      log_info_msg "\n Stopping wpa_supplicant on the $1 interface..."

      if [ -e /run/wpa_supplicant/$1.pid ]; then
         kill -9 $(cat /run/wpa_supplicant/$1.pid)
         rm -f /run/wpa_supplicant/$1.pid /run/wpa_supplicant/$1
         evaluate_retval
      else
         log_warning_msg "\n wpa_supplicant already stopped on $1"
         exit 0
      fi
   ;;

   *)
      echo "Usage: $0 [interface] {up|down}"
      exit 1
   ;;
esac

# End services/wpa
