#!/bin/bash

if [ ! -n "$1" ] && [ ! -n "$2" ]; then
	echo "usage: <cmd> app_name"
	echo "app_name      the app's name, e.g. 'My Sample App.app'"
	exit 1
fi

dockplistfile="${HOME}/Library/Preferences/com.apple.dock.plist"

APPNAME=$1
NEWAPPNAME=$2

# check if the entry for the app to be added already exists
test=$(defaults read com.apple.dock persistent-apps | grep -i $APPNAME)
if [ "$test" == "" ] ; then
	echo "source app does not exist. quitting."
	exit 0 
fi

# kill the entry
nl=`echo "x" | tr 'x' '\34'`
appspost=`defaults read com.apple.dock persistent-apps | sed "s/^[()]$//;s/},/}$nl/" | tr '\n\34' '\00\n'| grep -va "$APPNAME" | tr '\n\00' ',\n' | sed 's/^,$//'`
defaults write com.apple.dock persistent-apps '($appspost)'

# add the 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>$NEWAPPNAME</string>
				<key>_CFURLStringType</key>
				<integer>0</integer>
			</dict>
		</dict>
	</dict>"

killall -HUP Dock
