#!/bin/bash -x
# This script creates the final official release

# The script must be called with a single argument, containing the
# dot-separated major.minor.pl version string, e.g. "R-build-dist 2.10.0"

# Be very careful in making changes to it, as incorrect
# actions may be difficult to revert

# These two lines require local customization
LOCALDIR=$HOME
RELDIR=$HOME/R-release/
CRANDIR=cran.r-project.org:/srv/ftp/pub/R/src/base
exec > $RELDIR/build-dist.log 2>&1

#--- no changes should be necessary below this line
REL=$*
IFS=. read major minor pl << EOF
$*
EOF
TAG=R-$major-$minor-$pl

BASEDIR=$LOCALDIR/r-release-branch
SRCDIR=$BASEDIR/R
BUILDDIR=$BASEDIR/BUILD-dist
REPOS=https://svn.r-project.org/R
umask 022
#
# There is a remote risk that someone updated configure in SVN in a
# way that can cause a conflict
#
cd $SRCDIR
svn up --accept theirs-full || exit 1
echo $REL > VERSION
tools/rsync-recommended || exit 1
svn commit -m "Prepare for release $REL"
svn up
cd ..
rm -rf $BUILDDIR
mkdir $BUILDDIR
cd $BUILDDIR
# Local config. Required on MacOS for Tcl/Tk, CPPFLAGS, LDFLAGS.
cp ../config.site .
../R/configure --enable-maintainer-mode || exit 1
make -j4 || exit 1
make dist || exit 1
#
cd $SRCDIR  
svn cp -m "Tag version $REL" . $REPOS/tags/$TAG 
#
cd $BUILDDIR
RNOW=`echo R*.tar.gz`
cp $RNOW $RELDIR/R-$major
# XZ compressed version
RNOWBASE=`basename -s .gz  $RNOW`
RNOWXZ=$RNOWBASE.xz
gunzip -c $RNOW | xz -9e > $RNOWXZ
cp $RNOWXZ $RELDIR/R-$major
## (This will break whe we get to NEWS.10, but...)
cp doc/{FAQ,RESOURCES,COPYING*,AUTHORS,THANKS,NEWS{,.[0-9]}} $RELDIR
# cp doc/html/{NEWS.html,R.css} $RELDIR
#
cd $SRCDIR
cp README INSTALL  $RELDIR
#
cd $RELDIR
ln -sf R-$major/$RNOW R-latest.tar.gz
ln -sf R-$major/$RNOWXZ R-latest.tar.xz
#
# Update VERSION-INFO.dcf
#
VERSIONINFO=$RELDIR/VERSION-INFO.dcf
Rscript - << EOF
x <- read.dcf("$VERSIONINFO")
thisx <- c("Release","Nickname","Date")
oldx <- c("Old-release", "Old-nick", "Old-date")
nextx <- c("Next-release", "Next-nick", "Next-date")
pl <- $pl
if (pl == 0) x[, oldx] <- x[, thisx]
x[, thisx] <- x[, nextx]
x[, nextx] <- ""
write.dcf(x, file="$VERSIONINFO")
EOF
#
# Rsync step: Don't delete anything at destination
#
rsync -aOvuz --no-p $RELDIR/ $CRANDIR
#
# Update version info in r-release-branch:
#
cd $SRCDIR
echo $REL "Patched"  > VERSION
svn commit -m "setup for patched version"
svn up

#
cat <<EOF
Done.
REMEMBER:
    Update the developer homepage with new version info
    Update the project homepage too
    Make announcement on R-announce
EOF