#!/bin/sh

PLIST="$HOME/.MacOSX/environment.plist"
SLEEP_TIME=10
# Uncomment following to echo launchctl commands to stdout
# Key StandardOutPath will have to be set in the plist file
# (au.id.pbw.plist2launchctl) for output to be captured.
#ECHO_TO_STDOUT=true

one_cmd () {
    eval "$@"
}

[[ -e "$SHFILE" ]] && {
    rm "$SHFILE"
    [[ $? -eq 1 ]] && {
	echo "$SHFILE" cannot be removed. >&2
	exit 1
    }
}

cmd_list=`cat "$PLIST" | \
sed -En \
'/^[[:space:]]*<key>(.*)<\/key>[[:space:]]*/ {
s//launchctl setenv \1 /
N
}
/^.*<string>.*[[:space:]].*<\/string>.*$/ {
d
}
/^(launchctl .*)\n[[:space:]]*<string>(.+)<\/string>[[:space:]]*$/ {
s//\1\2/
p
d
}'`

[[ -n "$ECHO_TO_STDOUT" ]] && echo "$cmd_list"

echo "$cmd_list" | while read line; do one_cmd $line; done

[[ -n "$ECHO_TO_STDOUT" ]] && echo Sleeping in plist2launchctl

# Sleep for a while so launchd doesn't get upset
[[ -n "$SLEEP_TIME" ]] && sleep "$SLEEP_TIME"
