#!/bin/sh

# fixAppleScriptApp:
# This script changes the application bundle of a compiled AppleScript
# (one that has been saved as an application bundle)
# so that the application name is used instead of "applet".
# The first command-line argument is the path to the .app bundle
#
# If you want to change the "creator code" of the application
# (by default, all compiled AppleScripts have a creator code of "aplt")
# supply the desired 4-character code as a second command-line argument.
#
# Example usages:
# fixAppleScriptApp ~/MyAppleScripts/foo.app
# fixAppleScriptApp ~/MyAppleScripts/foo.app "ABCD"
#
# Cameron Hayne (macdev@hayne.net)  January 2007

scriptname=`basename $0`
if [ $# -lt 1 ]; then
    echo "Usage: $scriptname appPath [creatorCode]"
    exit -1
fi
if [ $# -gt 2 ]; then
    echo "Usage: $scriptname appPath [creatorCode]"
    exit -1
fi

appPath=$1
if [ $# -eq 2 ]; then
    creatorCode=$2
    if [ ${#creatorCode} -ne 4 ]; then
        echo "$scriptname: creatorCode should be 4 characters"
        exit -1
    fi
else
    creatorCode=""
fi

if [ ! -e "$appPath" ]; then
    echo "No such file ($appPath)"
    exit
fi

contents="$appPath/Contents"
info="$contents/Info"
if [ ! -e "$info.plist" ]; then
    echo "No such file ($info.plist)"
    exit
fi
macos="$contents/MacOS"
if [ ! -d "$macos" ]; then
    echo "No such directory ($macos)"
    exit
fi
resources="$contents/Resources"
if [ ! -d "$resources" ]; then
    echo "No such directory ($resources)"
    exit
fi

appName=`basename $appPath .app`

/usr/bin/defaults write "$info" CFBundleExecutable $appName
/usr/bin/defaults write "$info" CFBundleIconFile $appName

if [ "$creatorCode" != "" ]; then
    /usr/bin/defaults write "$info" CFBundleSignature $creatorCode
    echo -n "APPL$creatorCode" > "$contents/PkgInfo"
fi

if [ -f "$macos/applet" ]; then
    /bin/mv "$macos/applet" "$macos/$appName"
fi
if [ -f "$resources/applet.icns" ]; then
    /bin/mv "$resources/applet.icns" "$resources/$appName.icns"
fi
if [ -f "$resources/applet.rsrc" ]; then
    /bin/mv "$resources/applet.rsrc" "$resources/$appName.rsrc"
fi

# since the 'defaults' command seems to change the plist to binary
# we need to convert it back to the original 'xml1' (human-readable) format
/usr/bin/plutil -convert xml1 "$info.plist"

# finally, we need to 'touch' the .app file in order to force a refresh
# since the app attributes are cached in the launch services database
/usr/bin/touch "$appPath"

