#! /bin/bash
# Originally contributed by Neuro: http://bbs.archlinux.org/viewtopic.php?pid=278148#p278148

. /usr/lib/network/network.subr
. /usr/lib/network/wireless.subr
. /etc/rc.conf
. /etc/rc.d/functions
# wifi_auto
#   autoconnect wireless interface
#   $1 - wireless interface

wifi_auto()
{
    interface=$1; RETRIES=6
    stat_busy "Scanning for networks"

    ifconfig $interface up
    networks="$(list_networks $interface)"

    if [[ ! "$networks" ]]; then
        stat_append "- No networks available."
        stat_fail
        exit 1
    fi

    while read essid; do
        # Find CONNECTION=wireless, ESSID=$essid, INTERFACE=$interface
        for $network in /etc/network.d/*; do
            load_profile $(basename $network)
            if [[ "$CONNECTION" = "wireless" -a "$essid" = "$ESSID" \
                  "$interface" = "$INTERFACE" ]]; then
                stat_done
                netcfg2 $(basename $network)
                exit $?
            fi
            ${CONNECTION}_clean_scope
        done
    done < $networks
    
    stat_append "- No profiles matched the found networks"
    stat_fail
    exit 1
}

if [[ $(id -u) -ne 0 ]]; then
    err "This script needs to be run with root priviledges"
    exit 1
fi
if [[ -z $1 ]]; then
    err "Please supply an interface to connect"
    exit 1
fi
wifi_auto $1
  
