#!/bin/sh -e
#
# We currently assume this script is run from the source directory
# (otherwise set a different value for SOURCE_DIR); the
# dummy_export script also makes certain assumption

set -o errexit

if [ -z $1 ]; then
	echo "usage: $0 <CVS username>"
	exit
fi

CVS_USERNAME=$1
CVSROOT=":pserver:${CVS_USERNAME}@www.mozdev.org:/cvs"
SOURCE_DIR=`pwd`
DOWNLOADS_DIR="$SOURCE_DIR/../../downloads"
BUILDTOOLS_DIR="$SOURCE_DIR/../buildtools"

# determine version number
VERSION=`grep VERSION=\" dobuild | cut -d\" -f2 | head -1`
SHORTNAME=`grep SHORTNAME=\" dobuild | cut -d\" -f2`
USCORED_VERSION=`echo $VERSION | tr . _`
CAPS_SHORTNAME=`echo ${SHORTNAME} | tr a-z A-Z`
RELEASE_TAG="${CAPS_SHORTNAME}_RELEASE_${USCORED_VERSION}"
# this causes the dobuild script not to build a beta version
export EXTENSION_RELEASE=1

# create new version directory

if [ ! -d "${DOWNLOADS_DIR}/${VERSION}" ]; then
        mkdir "${DOWNLOADS_DIR}/${VERSION}"
fi

# build the release versions and place them in the appropriate directories

(./dobuild suitelegacy && ./dobuild suiterunner && ./dobuild tbird) || exit

for target in tbird suiterunner suitelegacy; do
        cp build/${target}/${SHORTNAME}_${VERSION}_${target}.xpi  ${DOWNLOADS_DIR}/${VERSION}/${SHORTNAME}_${target}.xpi
        cp build/${target}/${SHORTNAME}_${VERSION}_${target}.xpi ${DOWNLOADS_DIR}/latest/${SHORTNAME}_${target}.xpi
done


# create a CVS tag for the code used to build the release

cd ${SOURCE_DIR}
until cvs -d $CVSROOT tag -d ${RELEASE_TAG}; do : ; done
until cvs -d $CVSROOT tag ${RELEASE_TAG}; do : ; done

cd ${BUILDTOOLS_DIR}
until cvs -d $CVSROOT tag -d ${RELEASE_TAG}; do : ; done
until cvs -d $CVSROOT tag ${RELEASE_TAG}; do : ; done

cd ${SOURCE_DIR}
# Workaround for a mozdev cvs tagging bug, see
# https://www.mozdev.org/bugs/show_bug.cgi?id=14797
# and
# http://www.mozdev.org/drupal/wiki/MozdevCVSTipsTroubleshooting
# for details
until ${SOURCE_DIR}/dummy_export ${CVS_USERNAME}; do : ; done

# add the release to the CVS repository
# (it gets propagated to the mozdev download mirrors)

cd ${DOWNLOADS_DIR}

if [ ! -e ${VERSION}/CVS ]; then
	until cvs -d $CVSROOT add ${VERSION}/; do : ; done
fi
XPI_ENTIRES_IN_VERSION_DIR=`grep xpi ${VERSION}/CVS/Entries | wc -l`
if [ ${XPI_ENTIRES_IN_VERSION_DIR} == 0 ]; then
        until cvs -d $CVSROOT add `ls ${VERSION}/*.xpi`; do : ; done
fi
until cvs -d $CVSROOT ci ${VERSION}/ latest/; do : ; done
