#!/bin/sh

## OSX cmdline utility
## changes the icon of an app (or any other folder)

# example iconfile: /System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/HomeFolderIcon.icns

OLDDIR=$(pwd)

usage () {
  echo "$0 <app or directory(writeable)> <iconfile.icns>" 1>&2
  exit 1
}

mywhich() {
 for i in $@
 do
   if [ -x "$(which $i)" ]; then
     echo "$(which $i)"
     return
   fi
 done
 echo "unable to find executable: $@" 1>&2
 exit 1
}

APP=$1
ICON=$2

DEVTOOLS=/Developer/Tools
REZ=$(mywhich Rez ${DEVTOOLS}/Rez)
SETFILE=$(mywhich SetFile ${DEVTOOLS}/SetFile)

if [ "x${REZ}" = "x" ]; then exit 1; fi
if [ "x${SETFILE}" = "x" ]; then exit 1; fi

if [ -f "${ICON}" ]; then
 :
else
 if [ -f "${OLDDIR}/${ICON}" ]; then
   ICON="${OLDDIR}/${ICON}"
 else
   usage
 fi
fi

if [ -d "${APP}" ]; then
 # this is the output file
 ICONFILE=$'Icon\r'
 RSRCFILE="${ICONFILE}"
 DIR=${APP}
else
 if [ -f "${APP}" ]; then
  :
 else
  usage
 fi
 DIR=${APP%/*}
 if [ "x${DIR}" = "x" ]; then
   DIR=.
 fi
 if [ "x${DIR}" = "x${APP}" ]; then
   DIR=.
 fi

 # this is the output file
 ICONFILE=${APP##*/}
 RSRCFILE="${ICONFILE}.r"
fi

echo DIR $DIR
echo ICO $ICONFILE
echo RSR $RSRCFILE

cd "${DIR}"

touch "${RSRCFILE}" || usage
cat << EOF > "${RSRCFILE}"
/*
 * process this file with: 
 *     ${REZ} <thisfile> -o <file-to-add-icon-to>
 * after that, enable the icon with
 *     ${SETFILE} -a C <file-to-add-icon-to>
 */
read 'icns' (-16455) "${ICON}";
EOF

Rez "${RSRCFILE}" -o "${ICONFILE}" 
if [ "x${RSRCFILE}" = "x${ICONFILE}" ]; then
 # we are woriking on a directory
 SetFile -a C .
else
 # we are woriking on a file
 SetFile -a C "${ICONFILE}"
 rm "${RSRCFILE}"
fi

