#!/usr/bin/env php
<?php
$location_cmd = "/usr/sbin/scselect";
$scan_cmd = "/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport";
$locations = array();
$current_location = NULL;
$new_location = NULL;
exec($location_cmd, $rows, $error_code);
if($error_code)
{
trigger_error("Location command failed: '{$location_cmd}'");
die($error_code);
}
foreach($rows as $row)
{
if(preg_match("#(?<selected>\*\s+)?(?<id>[-0-9A-F]+)\s+\((?<name>.*)\)#", $row, $m))
{
if($m['selected'])
{
$current_location = $m['id'];
}
$locations[$m['id']] = $m['name'];
}
}
if(!$locations)
{
trigger_error("No locations found");
die(1);
}
$ssid = parse_ini_file(__DIR__ . '/ssid.ini');
if(!$ssid)
{
trigger_error("No ssid-settings found");
die(1);
}
exec("{$scan_cmd} -s", $rows, $error_code);
if($error_code)
{
trigger_error("Scan command failed: '{$scan_cmd} -s'");
die($error_code);
}
foreach($rows as $row)
{
if(preg_match("#^\s*\b(?<name>.*)\b (?<address>[0-9a-f][0-9a-f](:[0-9a-f][0-9a-f]){5}) #", $row, $m))
{
if(!empty($ssid[$m['address']]))
{
$new_location = $ssid[$m['address']];
break;
}
if(!empty($ssid[$m['name']]))
{
$new_location = $ssid[$m['name']];
break;
}
}
}
if(!$new_location)
{
if(!empty($ssid['*']))
{
$new_location = $ssid['*'];
}
}
if(!$new_location)
{
die(0);
}
if(empty($locations[$new_location]))
{
$location_by_name = array_flip($locations);
if(empty($location_by_name[$new_location]))
{
trigger_error("Unknown Location: '{$new_location}'" . PHP_EOL . print_r($ssid, TRUE));
die(1);
}
$new_location = $location_by_name[$new_location];
}
if($new_location == $current_location)
{
die(0);
}
if($current_location AND !empty($locations[$current_location]))
{
echo "Switching from '{$locations[$current_location]}' ({$current_location}) to '{$locations[$new_location]}' ({$new_location})" . PHP_EOL;
}
else
{
echo "Switching to '{$locations[$new_location]}' ({$new_location})" . PHP_EOL;
}
passthru($location_cmd . ' ' . escapeshellarg($new_location), $error_code);
die($error_code);
Comments