#!/bin/bash


######## ESSID@AP_MAC@ENC #######
device="eth1";
cells[1]="NETGEAR@00:0F:B5:15:12:C2@1008d82d11343234234234";
cells[2]="MJW@00:0F:AA:15:14:42@s:mypass";

#################################
iwc=iwconfig
iwl=iwlist
dhc=dhcpcd
tmp=/tmp/smartwlan.tmp

#    smartWLAN.sh Coypright (c) by Martin Willner, mw@antitachyon.com 
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA


function unregister() {
    killall -9 dhcpcd
    ifconfig $dev down
}
function register() {
#### scan
    $iwl $device sc 2> /dev/null > $tmp
    
### find
    size=${#cells[*]}
    
    for i in `seq 1 $size`; do
        essid=`echo ${cells[$i]} | cut -d@ -f1`
        mac=`echo ${cells[$i]} | cut -d@ -f2`
        enc=`echo ${cells[$i]} | cut -d@ -f3`
        foundmac="`grep $mac $tmp`"
        if [ "$foundmac" != "" ]; then
            echo "Found ESSID:"$essid" MAC:"$mac"";
            $iwc $device essid "$essid" 2>/dev/null
            $iwc $device enc "$enc" 2>/dev/null
            echo "Request IP....";
            dhcpcd $device
            ifconfig $device | grep "inet addr" 2>/dev/null
        fi
    done
}


if [ $# -lt 1 ]; then
    echo "usage: $0 [up|down]"
    exit;
fi

case $1 in
    up)
        register
        ;;
    down)
        unregister
        ;;
esac