#!/bin/bash

. /etc/sysconfig/wpa_supplicant

PROGRAM=/usr/sbin/wpa_supplicant
RUNLEVEL=3
NEEDS="+network"

CLI=/usr/sbin/wpa_cli
DROPFILE=/var/tmp/wpa_supplicant.drop

. /etc/init.d/smgl_init

start()
{
  required_executable /usr/sbin/iwconfig
  local IWCONFIG=`builtin echo $(/usr/sbin/iwconfig $INTERFACE 2>&1)`

  if [[ "$IWCONFIG" == $INTERFACE\ *Access\ Point:\ Not-Associated* ||
        "$IWCONFIG" == $INTERFACE\ *ESSID:off/any*                  ||
        "$IWCONFIG" == $INTERFACE\ *ESSID:\"\"*                     ]]; then
    echo Starting wpa_supplicant...
    $PROGRAM -B -i $INTERFACE -D $DRIVER -c $CONFIG -g $CONTROL > /dev/null >&1
    evaluate_retval
    echo "INTERFACE=\"$INTERFACE\"" > $DROPFILE
  elif [[ "$IWCONFIG" == $INTERFACE\ radio\ off* ]]; then
    echo $INTERFACE: radio off
    (exit 1)
    evaluate_retval
  elif [[ "$IWCONFIG" == $INTERFACE\ no\ wireless* ]]; then
    echo $INTERFACE: no wireless extensions
    (exit 1)
    evaluate_retval
  elif [[ "$IWCONFIG" == $INTERFACE\ No\ such* ]]; then
    echo $INTERFACE: no such device
    (exit 1)
    evaluate_retval
  else
    echo $INTERFACE: already connected
    (exit 1)
    evaluate_retval
  fi
}

stop()
{
  required_executable $CLI

  [[ -f $DROPFILE ]] && . $DROPFILE && rm $DROPFILE
  echo Stopping wpa_supplicant...
  $CLI -i $INTERFACE terminate 1 > /dev/null 2>&1
  evaluate_retval
}

status()
{
  required_executable $CLI
  $CLI status
}
