# Copyright (c) 2014, AllSeen Alliance. All rights reserved.
#
#    Permission to use, copy, modify, and/or distribute this software for any
#    purpose with or without fee is hereby granted, provided that the above
#    copyright notice and this permission notice appear in all copies.
#
#    THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
#    WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
#    MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
#    ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
#    WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
#    ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
#    OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#

findPid=$(pgrep /usr/sbin/wifi_scan)

if [ -z $findPid ]; then

    ## Get the scan results based on method available
    hasIw=$(which iw)
    hasIwList=$(which iwlist)

    if [ -n "$hasIw" ]; then
        result=$(/usr/sbin/parse_iw_wifi_scan)
    elif [ -n "$hasIwList" ]; then
        result=$(/usr/sbin/parse_iwlist_wifi_scan)
    fi

    ## Sort the results based on signal strength and print it to the file
    if [ -n "$result" ]; then
        printf "$result" | sort -n -r | awk '{sep="";for (i=4;i<=NF;i++) {printf "%s%s",sep, $i;sep=" "}; printf "\t"$3"\n"}' | sort | uniq > /tmp/wifi_scan_results
    fi
fi