#!/bin/bash
#
# Usage: nightly [cron]  (uses RDIRS)
#
# nightly  -> svn up -> rsr
#  -> build $1  : configure + make + check + create framework
#  +  build Mac GUI
#  -> pkg $1       : sign, package, sign
#
# Optional env vars:
# rebuild=no   - do not call build (but deploy and FW must match!)
#
# NOTE: packaging step re-signs all binaries and adds entitlements,
#       so packaged version is not identical to the original build!

: ${BASE=/Volumes/Builds/R4}
: ${RDIRS=`cat $BASE/builds`}

if [ -z "$RDIRS" ]; then
    echo "*** ERROR: RDIRS are not set and $BASE/builds has no valid entries" >&2
    echo "           Please set RDIRS or populate $BASE/builds" >&2
    exit 1
fi

## make sure we run in C locale due to a bug in sed
export LANG=C

RBUILDS="$BASE"

## find SVN
if [ -z "$SVN" ]; then
    for i in /opt/R/arm64/bin /opt/R/x86_64/bin /usr/local/bin; do
	if "$i/svn" --version >/dev/null 2>&1; then
	    SVN="$i/svn"
	    break
	fi
    done
fi
: ${SVN=svn}

## for oscode
. $BASE/common

if [ -e /opt/R/$ARCH/bin ]; then
    export PATH=/opt/R/$ARCH/bin:$PATH
fi

export PATH=/opt/gfortran/bin:$PATH

if [ -z "$JOBID" ]; then
    JOBID=nightly-$$-`date +%s`
    export JOBID
fi
LOCKJOB=`cat "$BASE/LOCK" 2>/dev/null`
if [ -n "$LOCKJOB" -a "$LOCKJOB" != "$JOBID" ]; then
    echo "ERROR: build locked by $LOCKJOB (I am $JOBID)" >&2
    exit 1
fi
echo $JOBID > "$BASE/LOCK"

echo "Starting job $JOBID"

date > $BASE/nightly.log

rm -f $BASE/GUIs $BASE/R-GUI-*.tar.gz

: ${rebuild=yes}
: ${svn_update=yes}

for RD in $RDIRS; do
    echo "$RD"
    ok=yes
    ver=`sed -E 's:^([0-9][.][0-9]+)[.].*:\1:' $RD/VERSION`
    echo "  R $ver"
    if [ "$rebuild" = yes ]; then
	if [ -e $BASE/$RD/.svn -a "${svn_update}" = yes ]; then
	    echo "SVN update on $RD" >> $BASE/nightly.log
	    cd $BASE/$RD
	    if ! $SVN up 2>> $BASE/nightly.log; then
		echo FATAL: SVN update FAILED >> $BASE/nightly.log;
		ok=no
	    fi
	    tools/rsync-recommended 2>> $BASE/nightly.log
	fi
	cd $BASE
	if [ -e R-${ver}-gfortran.tar.xz ]; then
	    echo " - unpacking R-${ver}-gfortran.tar.xz"
	    tar fxj R-${ver}-gfortran.tar.xz -C /
	    /opt/gfortran/bin/gfortran --version
	fi
	if ! ./build $RD; then ok=no; fi	
    fi

    if [ $ok = yes ]; then
	cd $BASE
	$BASE/build-gui $RD

	rm -f $BASE/deploy/$oscode/$RD/$RD-$oscode.pkg $BASE/deploy/$oscode/$RD/$RD-$oscode-signed.pkg $BASE/deploy/$oscode/$RD/$RD.pkg

	## run packaging step
	echo "Calling packaging/build.sh $RD"
	sh $BASE/packaging/build.sh "$RD"

	if [ -x $BASE/notarize -a -e "$BASE/deploy/$TNAME/$RD/$RD.pkg" ]; then
	    cp -c $BASE/deploy/$TNAME/$RD/$RD.pkg $BASE/deploy/$TNAME/$RD/$RD-$ARCH.pkg
	    RPKG="$BASE/deploy/$TNAME/$RD/$RD-$ARCH.pkg"
	    echo "Notarizing $RPKG"
	    $BASE/notarize "$RPKG"
	fi
    fi
done

echo "Removing lock for $JOBID"
rm -f "$BASE/LOCK"

if [ "$1" = cron -o "$2" = cron ]; then
    cd $BASE
    ./sync.out cron
fi