{ pkgs, ... }: { launchd.user.agents.locationchanger = { serviceConfig = { Label = "org.nixos.locationchanger"; RunAtLoad = true; WatchPaths = [ "/Library/Preferences/SystemConfiguration" ]; }; script = '' # This script changes network location based on the name of Wi-Fi network. exec 2>&1 >> $HOME/Library/Logs/LocationChanger.log sleep 3 ts() { date +"[%Y-%m-%d %H:%M] $*" } ID=`whoami` if [ "$ID" == "root" ]; then ts "Running as root will read a bad config, exiting." exit 1; fi SSID=`networksetup -listallhardwareports | awk '/Wi-Fi/{getline; print $2}' | xargs networksetup -getairportnetwork | awk '{print $NF}'` LOCATION_NAMES=`networksetup -listlocations` CURRENT_LOCATION=`networksetup -getcurrentlocation` CONFIG_FILE=$HOME/.locations/locations.conf ts "Connected to '$SSID'" ts "Probing '$CONFIG_FILE'" if [ -f $CONFIG_FILE ]; then ts "Reading to '$CONFIG_FILE'" ESSID=`echo "$SSID" | sed 's/[.[\*^$]/\\\\&/g'` NEW_SSID=`grep "^$ESSID=" $CONFIG_FILE | cut -d = -f 2` if [ "$NEW_SSID" != "" ]; then ts "Will switch the location to '$NEW_SSID' (configuration file)" SSID=$NEW_SSID else ts "Will switch the location to '$SSID'" fi fi ESSID=`echo "$SSID" | sed 's/[.[\*^$]/\\\\&/g'` if echo "$LOCATION_NAMES" | grep -q "^$ESSID$"; then NEW_LOCATION="$SSID" else if echo "$LOCATION_NAMES" | grep -q "^Automatic$"; then NEW_LOCATION=Automatic ts "Location '$SSID' was not found. Will default to 'Automatic'" else ts "Location '$SSID' was not found. The following locations are available: $LOCATION_NAMES" exit 1 fi fi if [ "$NEW_LOCATION" != "" ]; then if [ "$NEW_LOCATION" != "$CURRENT_LOCATION" ]; then ts "Changing the location to '$NEW_LOCATION'" scselect "$NEW_LOCATION" SCRIPT="$HOME/.locations/$NEW_LOCATION" if [ -f "$SCRIPT" ]; then ts "Running '$SCRIPT'" "$SCRIPT" fi else ts "Already at '$NEW_LOCATION'" fi fi ''; }; }