#!/bin/bash

# $Id: default.in 70 2004-02-08 20:18:25Z lennart $

# This file is part of waproamd.
#
# waproamd 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.
#
# waproamd 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 waproamd; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.

KEYDIR="/etc/waproamd/keys"

if [ -z "$AP" -o -z "$IFACE" ] ; then
   echo "Corrupt environment" > /dev/stderr
   exit 1
fi

AP_UC="$(echo $AP | tr [a-f] [A-F])"
METHOD=open
for M in aes wep ; do
    for F in "$AP" "$AP_UC" "essid:$ESSID_ESCAPED" ; do
        if test -r "$KEYDIR/$F.$M" ; then 
            METHOD="$M"
            FILE="$F"
            break
         fi
    done
    [ "x$METHOD" != "xopen" ] && break
done

[ "x$1" = "xstart" ] && echo "Setting policy '$METHOD'"

case "$1.$METHOD" in
    start.aes)
        aeswepd -i "$IFACE" -w -F "$KEYDIR/$FILE.aes"
        iwconfig "$IFACE" key on 2> /dev/null
        ;;

    stop.aes)
        aeswepd -i "$IFACE" -kW
        iwconfig "$IFACE" key off 2> /dev/null
        ;;
    
    start.wep)
	[ -z "$ESSID" ] || iwconfig "$IFACE" essid "$ESSID"
        KEY="$(cat $KEYDIR/$FILE.wep)"
        iwconfig "$IFACE" key [1] 2> /dev/null
        iwconfig "$IFACE" key restricted 2> /dev/null
	[ -z "$KEY" ] || iwconfig $IFACE key "$KEY"
        iwconfig "$IFACE" key on 2> /dev/null
        ;;

    *.open|stop.wep)
        iwconfig "$IFACE" key off 2> /dev/null
        ;;
    *)
        echo "Unknown command\n" > /dev/stderr
	exit 1
        ;;
esac

[ "$1" = "start" ] && exec /etc/waproamd/waproamd.action "$IFACE" up
[ "$1" = "stop" ] && exec /etc/waproamd/waproamd.action "$IFACE" down

exit 0
