#/bin/sh

# This script will parse up the output of the wpa_cli (v0.6.9) scan results
#  it it meant to be consumed by the camera server which will use fgets and sscanf
# to parse it up, to get the SSID, signal strength, and ad-hoc and security flags

#----------------------------
# helper script for php parsing to remove unknown security type entries
# ( should be run AFTER the square brackets around IBSS are converted to curly braces )
php_secfix=$( cat <<PHPCMD_SECFIX
# look for string in brackets
if ( preg_match( '/\[[^\]]*.\]/',  \$argn ) )
{
    # if it's a known type (WPA or WEP), print the line
    if ( preg_match('/\[WPA-PSK\]/', \$argn )  ||  preg_match('/\[WEP\]/', \$argn ) )
    {
        echo \$argn,"\n";
    }
}
# if there is no string in brackets, that's ok too, it means it is open, so print it
else
{
     echo \$argn,"\n";
}
PHPCMD_SECFIX
)


#----------------------------

wpa_cli scan_re|\
# only use lines with mac address
    grep : | \
# remove hidden SSIDs
    grep -v "<hidden>" |\
# reorder, and comma-delimit, and add an extra space for the flags in case it's empty (to simplify parsing)
    awk -F'	' '{print $3","$4" ,"$5","}' | \
# change to curly brace for ad-hoc
    sed 's/\[IBSS\]/\{ADHOC\}/' |  \
# strip out extra wpa junk (since WPA-PSK-* and WPA2-PSK-* are the same from our configuration perspective)
    sed 's/\[WPA2\-PSK.*\]/\[WPA-PSK\]/' |  \
    sed 's/\[WPA\-PSK.*\]/\[WPA-PSK\]/' |  \
# remove unknown security types
    php -R "$php_secfix" 2>/dev/null | \
# order by signal strength (the first item)
    sort -nr                            
#----------------------------
