#!/usr/bin/perl
# Simple script that checks for available access points
# and then sets a certain ESSID, WEP key, etc, based on them
# (C) 2003 Jelmer Vernooij <jelmer@samba.org>

use Getopt::Std;

my $version = "0.3";
my $timeout = 60;

our $iwlist_path = "/sbin/iwlist";
our $configfile = "/etc/wlandetect.conf";

$current_device = "";

our %interfaces = ();
our %current = ();

sub read_interfaces {
	open IWLIST, "$iwlist_path scan 2>/dev/null |" or die("Can't run iwlist!");
	while(<IWLIST>) {
		if(/([^ ]+)([ \t]+)Scan completed :/) {
			$current_device = $1;
		} elsif(/.*Address: (..):(..):(..):(..):(..):(..)/) {
			$interfaces{$current_device}{"$1:$2:$3:$4:$5:$6"} = 1;
		} elsif(/.*ESSID:"(.*)"/) {
			$interfaces{$current_device}{$1} = 1;
		}
	}

	close IWLIST;
}

sub set_interfaces {
	foreach (keys %interfaces) {
		$dev = $_;
		my $l = 0;

		# Check whether interface is connected

		open MAPPINGS, $configfile or die("Can't find configuration file");
		while(<MAPPINGS>) {
			$l++;
			if(/^#.*$/) {
				# Ignore comments
			} elsif(/([^ \t]+)([ \t]+)(.*)/) {
				if($interfaces{$dev}{$1} == 1 && $cur{$dev} cmp $1) {
					$command = $3;
					$command =~ s/\@DEV\@/$dev/g;
					if(!$options{'d'}) { print "Executing '$command'\n"; }
					system($command);
					$cur{$dev} = $1;
					last;
				}
			} else {
				print "Unparseable line : '$_' in wlandetect.conf, line $l\n";
			}
		}
		close MAPPINGS;
	}
}

our %options = ();
getopts("dqht:", \%options);

print "Wlandetect $version\n(C) 2003 Jelmer Vernooij <jelmer\@samba.org>\n" unless defined $options{q};

if(defined $options{h}) {
	print "-d     Daemon mode (go to the background and try to keep connection open)\n";
	print "-q     Be quiet (don't show version info)\n";
	print "-t int Seconds to wait before searching for peers/AP's again (daemon mode only)[60]\n";
	print "-h     Print this help message\n";
	exit 0;
}

read_mappings;

# Execute this part once in a while
read_interfaces;

if(!$options{'d'}) {
	set_interfaces;
	exit 0;
}

# Fork 
if(fork() > 0) { exit 0; }

# Register process identifier 
if (open(PIDF, "> /var/run/wlandetect.pid")) {
	print PIDF $$;
	close(PIDF);
}

while(1) {
	sleep($timeout);
	set_interfaces;
}
