#!/bin/sh

WO54PATH=${NEXT_ROOT}
WO53PATH=/Developer/WebObjects53
TMPDIR=/tmp
WOBUILDPROPS=~/Library/wobuild.properties

if [ $# -ne 1 -o "$1" = "-h" ] ; then
  echo "Usage: $0 [53|54]"
  exit 1
fi

if [ $# -eq 1 ] ; then
  WOVERSION=
  echo "$1" | grep -qE "^5[34]" && WOVERSION=$1
  if [ "X" = "X${WOVERSION}" ] ; then
    echo "Unknown WebObjects Version: $1"
    exit 1
  fi
fi

WOSYSVERSION=
WOVERSIONFILE=${WO54PATH}/System/Library/Frameworks/JavaWebObjects.framework/Resources/version.plist
if [ -f ${WOVERSIONFILE} ] ; then
  WOSYSVERSION=`cat ${WOVERSIONFILE} | grep -A 1 CFBundleShortVersionString | \
    tail -1 | sed -e 's/^.*5\.\([0-9]\).*/5\1/'`
fi
if [ X${WOSYSVERSION} != X54 ] ; then
  echo WebObjects 5.4 is not currently installed
  exit
fi

if [ ! -d ${WO53PATH}/System -a ${WOVERSION} -eq 53 ] ; then
  if [ ! -f ${TMPDIR}/WebObjects5.3.3Update.pax.gz ] ; then
    cd ${TMPDIR}
    ftp http://supportdownload.apple.com/download.info.apple.com/Apple_Support_Area/Apple_Software_Updates/Mac_OS_X/downloads/061-2998.20070215.33woU/WebObjects5.3.3Update.dmg && \
    dd if=${TMPDIR}/WebObjects5.3.3Update.dmg bs=0x1000 skip=0xb12 of=WebObjects5.3.3Update.pax.gz > /dev/null 2>&1 && \
        rm ${TMPDIR}/WebObjects5.3.3Update.dmg
  fi
  mkdir -p ${WO53PATH}
  cd ${WO53PATH}
  pax -zrf ${TMPDIR}/WebObjects5.3.3Update.pax.gz > /dev/null 2>&1 && \
    rm ${TMPDIR}/WebObjects5.3.3Update.pax.gz 
fi

if [ -f ${WOBUILDPROPS} ]
then
  if [ ! -f ${WOBUILDPROPS}54 ] ; then
    cp ${WOBUILDPROPS} ${WOBUILDPROPS}54
  fi
  if [ ! -f ${WOBUILDPROPS}53 ] ; then
    cat ${WOBUILDPROPS} | sed -E "s@=${WO54PATH}/?(System|Lib|$)@=${WO53PATH}/\1@g ; s@/\$@@" > ${WOBUILDPROPS}53
  fi
else
  echo Cannot find ${WOBUILDPROPS}
  exit 1
fi

WOVERSTRING=`echo ${WOVERSION} | sed -E 's/^([0-9])/\1./'`
echo Setting wobuild.properties for WebObjects ${WOVERSTRING}
cp ${WOBUILDPROPS}${WOVERSION} ${WOBUILDPROPS}
