#!/bin/sh
APP=$1

# NOTES:
# - lion stores the bundle id or the path as a URL (uri encoded)
# - snow leopard stores the file path without special encoding (the file path contains the bundle name)

# find the bundle id as the application path is not unique in the dock plist config
BUNDLE_ID=$(/usr/libexec/PlistBuddy -c "Print :CFBundleIdentifier" "$1"/Contents/Info.plist)
# find the bundle name as the application path is not unique in the dock plist config
BUNDLE_NAME=$(/usr/libexec/PlistBuddy -c "Print :CFBundleName" "$1"/Contents/Info.plist)

# check if the entry for the app to be added already exists
defaults read com.apple.dock persistent-apps | grep -i "$BUNDLE_ID" 
grepresult=$?
if [ $grepresult -eq 0 ] ; then
	echo "entry already exists. quitting."
	exit 0
fi

# check if the path is already in the dock
defaults read com.apple.dock persistent-apps | grep -i "$BUNDLE_NAME"
grepresult=$?
if [ $grepresult -eq 0 ] ; then
	echo "entry already exists. quitting. (2)"
	exit 0
fi

# in case we are still here yet add the dock entry
defaults write com.apple.dock persistent-apps -array-add \
	"<dict>
		<key>tile-data</key>
		<dict>
			<key>file-data</key>
			<dict>
				<key>_CFURLString</key>
				<string>$APP</string>
				<key>_CFURLStringType</key>
				<integer>0</integer>
			</dict>
		</dict>
	</dict>"
	
dockplistfile="${HOME}/Library/Preferences/com.apple.dock.plist"

/usr/libexec/PlistBuddy -c save "${dockplistfile}"
/usr/bin/killall -HUP Dock

≠
