#!/bin/sh

board=$(cat /tmp/sysinfo/board_name)

WPS_LED=/sys/class/leds/blue/trigger

case "$board" in
ap151)
	WPS_LED=/sys/class/leds/ap151:green:wlan/trigger
	;;
esac

mode=$1


check_status()
{
    local active
    active=true
    call=$1
    while [ $active == true ]
    do
        running=false
        temp1=$(cat $WPS_LED)
        temp2=$(echo ${temp1##*\[})
        state=$(echo ${temp2%%]*})
        for dir in /var/run/hostapd-*; do
            [ -d "$dir" ] || continue
            for vap_dir in $dir/ath* $dir/wlan*; do
                [ -r "$vap_dir" ] || continue
                retval=$(eval $call)
                if [ \( $(echo "$retval" | grep -c '^RUNNING\|Active') -gt 0 \) -a \( $state != "timer" \) ]; then
                    running=true
                elif [ \( $(echo "$retval" | grep -c '^RUNNING\|Active') -gt 0 \) -a \( $state == "timer" \) ]; then
                    running=true
                fi
            done
        done
        if [ $running == false ]; then                                              
            echo none > $WPS_LED                                                                
            active=false                                      
        else                                                                                                      
            echo timer > $WPS_LED                                                               
        fi
        sleep 1
    done
}

check_clone()
{
    local active
    active=true
    
    while [ $active == true ]
    do
        temp1=$(cat $WPS_LED)
        temp2=$(echo ${temp1##*\[})
        state=$(echo ${temp2%%]*})
        retval=$(uci show wireless.wps_clone | grep -c 'running')
        
        if [ \( $retval -gt 0 \) -a \( $state != "timer" \) ]; then
            echo timer > $WPS_LED
        elif [ $retval -eq 0 ]; then
            active=false
            echo none > $WPS_LED
        fi
        sleep 1
    done
    
}

#save config
old_trigger=$(cat $WPS_LED | cut -d "[" -f2 | cut -d "]" -f1)

case $mode in
    pbc) check_status 'hostapd_cli -i "${vap_dir#"$dir/"}" -p "$dir" wps_get_status' ;;
    pin) check_status 'hostapd_cli -i "${vap_dir#"$dir/"}" -p "$dir" wps_get_pin_status' ;;
    clone) check_clone ;;
esac

#restore config
echo $old_trigger > $WPS_LED