#!/bin/bash
#
###########################################################################
#
# Variable and function definitions
#
MANAGER=pety
MODULE=gildas
RELEASEDIR=$HOME/www/dist
ARCHIVEDIR=$RELEASEDIR/archive/gildas
#
# Analytics script:
ANALYTICS="$HOME/gildas-dependencies/google/google-analytics.txt"
#
AUTHOR='J. Pety <pety@iram.fr>'
VERSION=`echo '$Revision: 1.28 $'|cut -d' ' -f2`
PROJECT='GILDAS <http://www.iram.fr/IRAMFR/GILDAS>'
#
PROGNAME=`basename $0`
#
function usage() {
    cat <<EOF 1>&2

This scripts enable easy release of sources, documentation, or both 
(default is both).

Warning: This script assumes that the IRAM rebuild is a success.

usage: $PROGNAME [kind]

kind:
  day    Release last fully compilable version (default)
  month  Release current state of the month branch
  dec07,jan08,... Release current state of the input monthly branch

options:
  -a     Release all (ie sources and documentation: equivalent to -ds)
  -d     Release documentation
  -s     Release sources
  -q     Quiet mode, ie send information to a log file instead of output
         it to screen
  -h     Show this help page
  -v     Show version information

EOF
}
#
function showversion() {
    echo "${PROGNAME} version ${VERSION}, by ${AUTHOR}"
    echo "Project: ${PROJECT}"
}
#
function message() {
    echo "${PROGNAME}: $1"
}
#
function error_exit() {
    echo 2>&1
    echo "${PROGNAME} error: $1" 2>&1
    echo 2>&1
    exit 2
}
#
###########################################################################
#
# Option parsing
#
OPTIND=1
while getopts adsqhv opt; do
    case "$opt" in
    a) documentation=1; sources=1;;
    d) documentation=1 ;;
    s) sources=1 ;;
    q) quiet=1 ;;
    v) showversion; exit 0 ;;
    h) usage; exit 0 ;;
    *) usage; exit 1 ;;
    esac
done
shift $(($OPTIND - 1))
#
# Default is to release both documentation and sources
if [ -z "$documentation" -a -z "$sources" ]; then
    documentation=1
    sources=1
fi
#
if [ $# -ne 1 ]; then
    usage
    exit 1
else
    case $1 in
	day) day=1; IN_VERSION=$1; RELEASEDIR=$RELEASEDIR/daily ;;
	month|jan??|feb??|mar??|apr??|may??|jun??|jul??|aug??|sep??|oct??|nov??|dec??) month=1; IN_VERSION=$1 ;;
	*)   usage; exit 1 ;;
    esac
fi
#
set -- # This line to avoid remanence effects.
#
###########################################################################
#
# Define log directory (create if needed) and log files
#
# Set $LOGDIR and $GAG_TAG
source $gagadmdir/define-version.sh
gagdefver $IN_VERSION  || error_exit "Defining calling 'gagdefver'"
unset gagdefver
if [ ! -d $LOGDIR ]; then
    mkdir -p $LOGDIR || error_exit "creating \$LOGDIR directory"
fi
#
# When quiet, make a log file with outputs and errors
#
if [ "$quiet" ]; then
    LOGFILE=$LOGDIR/release.log
    exec > $LOGFILE 2>&1
fi
LOGLS2HTML=$LOGDIR/ls2html.log
LOGCVSRELEASE=$LOGDIR/cvsrelease.log
#
###########################################################################
#
# Define CVSROOT with a user who has repository write access
#
export CVSROOT=:pserver:$MANAGER@cvs.iram.fr:/CVS/GILDAS
#
# Create release directory and go there
#
mkdir -p $RELEASEDIR || error_exit "making ${RELEASEDIR}"
cd $RELEASEDIR       || error_exit "going to ${RELEASEDIR}"
#
# Define release name
#
if [ "$month" ]; then
    #
    # Major version
    branch=$GAG_TAG
    branchopt="-T -b $branch"
    prev_month=`date -d "1 month ago" "+%b%y" | tr '[:upper:]' '[:lower:]'`
    prev_month=$prev_month"?"
    # Minor version
    if [ `cvs history -T | grep -c "${branch}:last"` -ge 1 ]; then
	for letter in a b c d e f g h i j k l m n o p q r s t u v w x y z; do
	    release=${branch}${letter}
	    if [ `cvs history -e | grep -c ${release}` -eq 0 ]; then
		# This version not found on the CVS: can use it.
		break 1;
	    else
		# There was already a version for this month: keep track
		# for later deletion.
		prev_month=$release
	    fi
	done
    else
	error_exit "Branch ${branch} does not exist"
    fi
    tag=$release
    vers=$branch
    #
elif [ "$day" ]; then
    #
    branchopt=""
    #
    # Get date of 'last' tag
    last_date=`cvs history -T | grep "last:day" | tail -1 | cut -d' ' -f2`
    #
    # Build daily release name
    release=`date -d "$last_date" '+%d%b%y'` || error_exit "Found $last_date as 'last' date"
    release=`echo $release | tr '[:upper:]' '[:lower:]'`
    #
    tag="last"
    vers=$tag
    #
fi
#
# Release sources
#
if [ "$sources" ]; then
    #
    # Release (first tag the existing branch for monthly release)
    message "Make ${release} source release using cvsrelease"
    cvsrelease -t $tag -r $release $branchopt "$MODULE-src" > $LOGCVSRELEASE 2>&1
    if [ "$?" -ne 0 ]; then
	cat $LOGCVSRELEASE
	error_exit "making ${release} source release"
    fi
    #
    # Get tag date-time
    if [ "$month" ]; then
	release_datetime=`cvs history -e | grep "$tag"     | tail -1 | cut -d' ' -f2-4`
    elif [ "$day" ]; then
	release_datetime=`cvs history -T | grep "last:day" | tail -1 | cut -d' ' -f2-4`
    fi
    #
    if [ -n "$release_datetime" ]; then
	#
	# Build release timestamp
	timestamp=`date -d "$release_datetime" "+%d%b%y %H:%M %Z"` || error_exit "Found $last_datetime as 'last' date-time"
	timestamp=`echo $timestamp | tr '[:upper:]' '[:lower:]'`
	GAG_VERS="$release ($timestamp)"
	#
	# Update VERSION file in archive
	message "Updating VERSION file with \"$GAG_VERS\""
	name=$MODULE-src-$release
	gunzip $name.tar.gz             || message "Could not gunzip $name.tar.gz"
	mkdir $name                     || message "Could not create $name directory"
	rm -f $name/VERSION
	echo $GAG_VERS > $name/VERSION
	tar -uf $name.tar $name/VERSION || message "Could not update archive $name.tar"
	gzip $name.tar                  || message "Could not gzip $name.tar"
	rm -rf $name                    || message "Could not remove $name directory"
	#
    else
	message "Could not find tag date-time"
    fi
fi
#
# Release documentation
#
if [ "$documentation" ]; then
    message "Make ${release} doc release"
    gagiram -em $vers  > /dev/null || error_exit "Selecting the version"
    go -e > /dev/null || error_exit "Going to the executable root directory"
    tar -czvf $RELEASEDIR/$MODULE-doc-$release.tar.gz doc > /dev/null || error_exit "Making the tar file"
fi
#
# Clean old release and update archive/index.html
#
if [ "$day" ]; then
    daynumber=10
    while [ $daynumber -le 365 ]; do
	dayname=`date -d "$daynumber days ago" +'%d%b%y' | tr '[:upper:]' '[:lower:]'`
	rm -rf $RELEASEDIR/$MODULE-src-$dayname.tar.gz
	rm -rf $RELEASEDIR/$MODULE-doc-$dayname.tar.gz
	daynumber=$[ daynumber + 1 ]
    done
    HREFATTR_CATEGORY="daily"
elif [ "$month" ]; then
    message "Moving $prev_month to $ARCHIVEDIR"
    # Do not complain if $prev_month is not found
    mv $RELEASEDIR/$MODULE-src-$prev_month.tar.gz $ARCHIVEDIR/.
    mv $RELEASEDIR/$MODULE-doc-$prev_month.tar.gz $ARCHIVEDIR/.
    cd $ARCHIVEDIR || error_exit "going to archive directory $ARCHIVEDIR"
    HREFATTR=" target=\"_blank\" onclick=\"_gaq.push(['_trackEvent','Gildas','archive',this.href]);\""
    ls2html -t "GILDAS download archive" -x index.html -s $ANALYTICS -a $HREFATTR > index.html 2> $LOGLS2HTML
    if [ "$?" -ne 0 ]; then
	cat $LOGLS2HTML
	error_exit "making index.html for archive directory $ARCHIVEDIR"
    fi
    HREFATTR_CATEGORY="stable"
fi
#
# Update ./index.html
#
cd $RELEASEDIR || error_exit "going to distrib directory $RELEASEDIR"
HREFATTR=" target=\"_blank\" onclick=\"_gaq.push(['_trackEvent','Gildas','$HREFATTR_CATEGORY',this.href]);\""
ls2html -t "GILDAS download area" -x index.html -s $ANALYTICS -a "$HREFATTR" > index.html 2> $LOGLS2HTML
if [ "$?" -ne 0 ]; then
    cat $LOGLS2HTML
    error_exit "making index.html for distrib directory $RELEASEDIR"
fi
#
###########################################################################
#
# Report success
#
# clean || error_exit "Cleaning old release"
message "It worked! Bye."
#
###########################################################################
