How to run a program if your Mac OS X system's configuration changes

My MacBook travels a lot and thus connects to various networks. Depending on the network it's connected to, I want it to start and stop some applications like a VPN client or instant messenger. As we have launchd and as all system configuration is a bunch of plist (read: plain xml) files located in /Library/Preferences/SystemConfiguration, we can easily script that:

  1. Create a shell script that does the real work and save it as ~/.syschange.sh. Mine looks like this:
    #!/bin/sh
    
    msg=""
    if ifconfig | grep -q "inet 10.0.23."; then
      # at work, stop VPN to corporate network, start IM
      echo 'tell application "VPN CLIENT" to quit' | osascript
      echo 'tell application "Adium" to launch' | osascript
      msg="Stopped VPN CLIENT, started Adium"
    elif ifconfig | grep -q "inet 172.17.0."; then
      # at home
      echo 'tell application "VPN CLIENT" to launch' | osascript
      echo 'tell application "Adium" to launch' | osascript
      msg="Started VPN CLIENT, started Adium"
    elif ifconfig | grep -q "inet 212.62.64."; then
      # at some fancy customer
      echo 'tell application "VPN CLIENT" to launch' | osascript
      echo 'tell application "Adium" to quit' | osascript
      msg="Started VPN CLIENT, stopped Adium"
    else
      msg="Nothing to do"
    fi
    logger -t "$0" "$msg"
    
  2. Make that script executable:
    chmod 0755 ~/.syschange.sh
    
  3. Create a plist file in Library/LaunchAgents in your home folder and name it SysChange.plist (or whatever name of prefer):
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN"
    	"http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
    <dict>
    	<key>Label</key>
    	<string>YOURNAME.SysChange</string>
    	<key>ProgramArguments</key>
    	<array>
    		<string>/Users/YOURNAME/.syschange.sh</string>
    	</array>
    	<key>WatchPaths</key>
    	<array>
    		<string>/Library/Preferences/SystemConfiguration</string>
    	</array>
    </dict>
    </plist>
    
    Of course you have to replace YOURNAME with your name. The Label can be more sophisticated, e.g. com.YOURDOMAINNAME.tools.SysChange.
  4. Instruct launchd to pickup that file:
    launchctl load /Users/YOURNAME/Library/LaunchAgents/SysChange.plist
    
  5. Open the Console and connect to different networks. Search for SysChange.