#!/bin/sh
#
# $1 - Bundle directory
# $2 - Name of wrapper shellscript
# $3 - Path of icon file
# $4 - Path of binary executable
# $5 - Path of plist template
# $6 - Creator
# $@ - Additional arguments for executable

set -e
BDIR=$1
SCRIPT=$2
ICON=$3
BIN=$4
PLIST=$5
CREATOR="$6"
shift 6
curdir=`pwd`
cd `dirname $0`
THISDIR=`pwd`
cd $curdir

BB=`basename $BIN`
BNAME="`basename \"$BDIR\" .app`"
BDNAME="`basename \"$BDIR\" .app`"
if test -z "$CREATOR" ; then
    CREATOR="????"
fi
mkdir -p "$BDIR/Contents/MacOS"
mkdir -p "$BDIR/Contents/Resources"
iconshort=`basename $ICON .icns`
if [ -n "$SCRIPT" ] ; then
    sed -e "s/_ICON_/$iconshort/" \
        -e "s/_EXECUTABLE_/$SCRIPT/" \
        -e "s/_BUNDLEID_/$SCRIPT/" \
        -e "s/_BNAME_/$BNAME/" \
        -e "s/_BDNAME_/$BDNAME/" \
        -e "s/_CREATOR_/$CREATOR/" < $PLIST > "$BDIR/Contents/Info.plist"
else
    sed -e "s/_ICON_/$iconshort/" \
        -e "s/_EXECUTABLE_/$BB/" \
        -e "s/_BUNDLEID_/$BB/" \
        -e "s/_BNAME_/$BNAME/" \
        -e "s/_BDNAME_/$BDNAME/" \
        -e "s/_CREATOR_/$CREATOR/" < $PLIST > "$BDIR/Contents/Info.plist"
fi
cp $ICON "$BDIR/Contents/Resources"
chmod u+w "$BDIR/Contents/Resources/$iconshort.icns"
echo "APPL$CREATOR" > "$BDIR/Contents/PkgInfo"
IPLNAME=$BB
if [ -n "$SCRIPT" ] ; then
    IPLNAME=$SCRIPT
    cat<<EOF>"$BDIR/Contents/MacOS/$SCRIPT"
#!/bin/sh
exec $BIN "\$@" $@
EOF
    chmod a+x "$BDIR/Contents/MacOS/$SCRIPT"
else
    rm -f "$BDIR/Contents/MacOS/$BB"
    ln -s "$BIN" "$BDIR/Contents/MacOS/$BB"
fi
for lng in en de ; do
    if test -f $THISDIR/$IPLNAME.$lng.infoplist ; then
        mkdir -p "$BDIR/Contents/Resources/$lng.lproj"
        iconv -t UTF-16 $THISDIR/$IPLNAME.$lng.infoplist \
            > "$BDIR/Contents/Resources/$lng.lproj/InfoPlist.strings"
    fi
done
