#!/bin/sh
#
# optional: set PKGONLY=1 if you want to package from the
#           currently installed files (otherwise tar balls are used)

# -- configurable paths needed for operation --
ROOT=/Builds/nightly
XCODE=/Developer

# force C locale due to bugs in sed
export LANG=C

# make sure the PATH contains sbin for chmod etc.
PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/X11/bin:/usr/local/bin
export PATH

if [ -z "$1" ]; then
    echo ''
    echo " Usage: $0 <r-name>"
    echo ''
    echo ' Note: must be run as root'
    echo ''
    exit 1
fi

DREL=`uname -r | sed 's:\..*::'`
## FIXME: why don't we use . common ??
case $DREL in
15)
    oscode=el-capitan
    ;;
13)
    oscode=mavericks
    ;;
*)
    oscode=snowleopard
    ;;
esac

WD=`pwd`
RNAME="$1"
PKGDIR="${ROOT}/packaging/leopard/"
arch=x86_64
DEP="${ROOT}/deploy/$oscode/$RNAME/"

# mkdoc uses BASE ...
: ${BASE="$ROOT"}
export BASE

rm -rf "$PKGDIR/R.pkg"

if [ -z "$PKGONLY" ]; then

if [ ! -e "${ROOT}/$oscode-sa-$arch/$RNAME.SUCCESS" ]; then
    echo "ERROR: the nightly build was not sucessful"
    echo "${ROOT}/$oscode-sa-$arch/$RNAME.SUCCESS"
    exit 1
fi

RTAR="$RNAME-$oscode-sa-$arch.tar.gz"
if [ ! -e "$DEP/$RTAR" ]; then
    echo "ERROR: cannot find tar ball $RTAR"
    exit 1
fi

echo "-- restoring framework and GUIs from tar balls"

GUI64=`ls $DEP/R-GUI-*-Release.tar.gz|sort|tail -n 1`
if [ -z "$GUI64" ]; then
    echo "ERROR: cannot find 64-bit R.app tar ball in $DEP/R-GUI-*-Release.tar.gz"
    exit 1
fi

if [ `id -u` != 0 ]; then
    echo "This script needs to be run as root so it can adjust permissions"
    exit 1
fi

echo "R: $DEP/$RTAR"
echo "GUI: $GUI64"

rm -rf /Library/Frameworks/R.framework
tar fxz "$DEP/$RTAR" -C /

rm -rf /Applications/R.app

tar fxz "$GUI64" -C /Applications/

else # PKGONLY=1
    echo "-- running in packaging mode only"
fi 

chown -Rh root:admin /Applications/R.app
chmod -R g+w /Applications/R.app

cd "$PKGDIR"
./mkdoc
rm -f "$DEP/$RNAME-$oscode.pkg"
${XCODE}/Applications/Utilities/PackageMaker.app/Contents/MacOS/PackageMaker -d R.pmdoc -o "$DEP/$RNAME-$oscode.pkg"
chown urbanek:admin "$DEP/$RNAME-$oscode.pkg"

echo ''
echo " Package created: $DEP/$RNAME-$oscode.pkg"
echo ''