#!/bin/sh
# chkconfig: 2345 25 75
### BEGIN INIT INFO
# Provides:          wpa_supplicant
# Required-Start:    $network
# Required-Stop:     $network
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start wpa_supplicant at boot time
# Description:       Enable service provided by wpa_supplicant.
# X-Start-Before:    
# X-Stop-After:      
# X-Timesys-Start-Number:  25
# X-Timesys-Stop-Number:  75
### END INIT INFO


PATH=/usr/bin:/bin:/usr/sbin:/sbin
DAEMON=wpa_supplicant
CONFIG_FILE=/etc/wpa_supplicant.conf
PID_FILE=/var/run/wpa_supplicant/pid
INTERFACE=wlan0
DRIVER=wext
DAEMON_OPTIONS="-B -c $CONFIG_FILE -P $PID_FILE -i$INTERFACE -D$DRIVER"

CTRL_INTERFACE="ctrl_interface=/var/run/wpa_supplicant"

create_config()
{
    printf "ctrl_interface=/var/run/wpa_supplicant\r\nctrl_interface_group=root\r\nupdate_config=1\r\n" > $CONFIG_FILE

    sync
}

check_config()
{
    if [[ -e $CONFIG_FILE ]]; then 
        if ! grep -q "ctrl_interface=/var/run/wpa_supplicant" $CONFIG_FILE ; then
            echo "ctrl_interface=/var/run/wpa_supplicant" >> $CONFIG_FILE
        fi
        if ! grep -q "update_config=1" $CONFIG_FILE ; then
            echo "update_config=1" >> $CONFIG_FILE
        fi
        if ! grep -q "ctrl_interface_group=root" $CONFIG_FILE ; then
            echo "ctrl_interface_group=root" >> $CONFIG_FILE
        fi
    else
        create_config
    fi
}


case "$1" in
    start)
        echo -n "Starting wpa_supplicant: "
        check_config

        modprobe unifi_sdio
        attempts=1
        until [ -e /dev/unifiudi0 ]; do
          if [ $attempts -gt 5 ]; then
            echo '[FAIL]'
            echo "--- No wireless device found ---"
            exit 1
          fi
          sleep $attempts
          attempts=$((attempts+1))
        done
        unifi_config --dev /dev/unifiudi0 --wifion
        ifconfig $INTERFACE up 2>/dev/null
        attempts=1
        until ifconfig -a $INTERFACE 2>/dev/null | grep -q '\bUP\b'; do
          if [ $attempts -gt 5 ]; then
            echo '[FAIL]'
            echo "--- No wireless interface found ---"
            exit 1
          fi
          sleep $attempts
          attempts=$((attempts+1))
        done
        $DAEMON -i $INTERFACE $DAEMON_OPTIONS && echo '[ OK ]' && exit 0
        echo '[FAIL]'
    ;;
    stop)
        if [ -f $PID_FILE ]; then
            echo -n "Stopping wpa_supplicant: "
            read PID < $PID_FILE
            kill $PID && \
              echo '[ OK ]' || echo '[FAIL]'
        else
            echo "pid file not found... is wpa_supplicant running?"
        fi
    ;;
    restart)
        $0 stop
        $0 start
    ;;
    *)
        echo "usage: $0 {start|stop|restart}"
    ;;
esac
