#!/usr/bin/php
<?php

//----------------------------------------------------------------------------
// Script settings. You should't have to change these.

define('FALLBACK', 'fallback');
define('SMTP', 'smtp');
define('SSID', 'ssid');

$paths['airport'] = '/System/Library/PrivateFrameworks/Apple80211.framework/Versions/A/Resources/airport';



//----------------------------------------------------------------------------
// Configuration. You should update this.


// Default location.
$locations[FALLBACK] = array(
  SMTP => array(
    'gmail1' => 'smtp.gmail.com:foo@gmail.com',
    'gmail2' => 'smtp.gmail.com:bar@gmail.com',
  ),
);

// UHasselt.
$uh_smtp = 'student.uhasselt.be:0623800';
$locations['UH'] = array(
  SSID => 'UHasselt-Public',
  SMTP => array(
    'gmail1' => $uh_smtp,
    'gmail1' => $uh_smtp,
  ),
);



//----------------------------------------------------------------------------
// Phase 1: detection.

echo "---DETECTION---\n";

// Detect SSID.
$ssid = exec("{$paths['airport']} -I | grep ' SSID:' | cut -d ':' -f 2 | tr -d ' '");
echo "Detected SSID: '$ssid'.\n";


// Try to determine the location by matching the SSID.
$location_id = FALSE;
foreach ($locations as $location => $config) {
  if ($location == FALLBACK)
    continue;

  echo "Location '$location'? (SSID '{$config[SSID]}')\t\t\t";
  if ($ssid == $config[SSID]) {
    $location_id = $location; 
    echo "Match!\n";
    break;
  }
  else
    echo "No match.\n";
}

// No SSID matched the location, so let's assign the automatic location.
if (!$location_id) {
  $location_id = FALLBACK;
  echo "Falling back to the default location.\n";
}

echo "Location: $location_id\n";



//----------------------------------------------------------------------------
// Phase 2: reactions.

echo "\n";
echo "---REACTIONS---\n";

// Update SMTP!
if (isset($locations[$location_id][SMTP])) {
  echo "SMTP\n";
  foreach ($locations[$location_id][SMTP] as $account => $smtp_server) {
    exec("osascript -e 'tell application \"Mail\" to set smtp server of account \"$account\" to smtp server \"$smtp_server\"'");
    echo "Set SMTP server of account $account to $smtp_server.\n";
  }
}
