#!/bin/bash
#
# Variable and function definitions
#
AUTHOR='S. Bardeau <gildas@iram.fr>'
VERSION=`echo '$Revision: 1.14 $' | cut -d' ' -f2`
PROJECT='MOPSIC (R.W.Zylka) / GILDAS <http://www.iram.fr/IRAMFR/GILDAS>'
PROGNAME=`basename $0`
#
# Administration
MANAGER=pety           # Account used for some non-anonymous commands
MODULE=mopsic
GILDASDIR=$HOME/gildas
MOPSICDIR=$HOME/mopsic
LOGFILE=$MOPSICDIR/logs/rebuild-mopsic-iram.txt
SYSFILE=rebuild-mopsic-iram.systems    # Default file where systems are read from
#
# Mail reports
RECIPIENTS="zylka bardeau pety"
MAILHEADER="[mopsic-compilation]"
#
###########################################################################
#
# Ensure a stable $gagadmdir to start the process
#
export gagadmdir=$GILDASDIR/gildas-admin
#
###########################################################################
#
# Load global functions
#
source $gagadmdir/rebuild-commons
#
###########################################################################
#
# Define local functions
#
function usage() {
    cat <<EOF 1>&2

Script used to build every month the monthly version several systems.
An abbreviated log is sent to the GILDAS maintainer. When restarted by
hand after a bug correction, this scripts tries hard to rebuild only
what is affected by the bug fix. This script is triggered by a cron job.

usage: $PROGNAME [-b] [-f <file>] [-h] [-v] version

version:
  month      Alias for current month e.g. apr09
  apr09,may09,...
  <other versions not yet supported>

options:
  -b         Make month branch starting at the current status
  -f <file>  Use $gagadmdir/<file> instead of $gagadmdir/$SYSFILE
  -l         Local build: $PROGNAME will read the builds from $SYSFILE,
             and will build only the ones matching the local system.
             Without this option, builds are performed on remote machines.
  -h         Show this help page
  -v         Show version information

EOF
}
#
function mybuild() {               # Examples:
    BUILDKIND=$1                   # exe
    HOST=$2                        # pctcp30
    EXEC_SYSTEM=$3                 # x86_64-fedora6
    SYSTEM=$3-$4                   # x86_64-fedora6-ifort
    COMPILER=$4                    # ifort
    GILDASREF=$5                   # mar08
    CONFIG=$6                      # staticlink
    #
    case $BUILDKIND in
	exe) BUILDOPT="-e -c $COMPILER -g $GILDASREF" ;;
	*) echo "$@: $BUILDKIND is an unsupported kind of build" >> $LOGFILE ; return 255
    esac
    #
    # Define $SYSCONF used by mybuild_message
    if [ -z $CONFIG ]; then
	SYSCONF="mopsic-$SYSTEM"          # mopsic-x86_64-fedora6-ifort
    else
	SYSCONF="mopsic-$SYSTEM-$CONFIG"  # mopsic-x86_64-fedora6-ifort-staticlink
	BUILDOPT="$BUILDOPT -o $CONFIG"
    fi
    #
    if [ "$localbuild" ]; then
	# Build is done locally for all builds matching the local system
	# (rebuild-mopsic-iram -l).
	if [ $EXEC_SYSTEM = $LOCAL_EXEC_SYSTEM ]; then
	    message "Matched $BUILDKIND $HOST $SYSTEM $GILDASREF $CONFIG"
	    # Execute in a subshell to avoid overwriting environment variables.
	    ( source $HOME/.bash_profile; \
		export GAG_ADDONS=yes; \
		source set-iram-gag-search-path ${COMPILER} && \
		${gagadmdir}/rebuild-mopsic ${BUILDOPT} ${GAG_TAG} )
	    status=$?
	    #
	else
	    # Skip. Nothing to do, nothing to check.
	    message "Skip $EXEC_SYSTEM."
	fi
	#
    elif [ $HOST = "local" ]; then
	# Built is done by another call to rebuild-mopsic-iram -l, in a
	# cron on a virtual machine. The successful build relies on the
	#  existence of the .success file in the log directory.
	if [ -e "$LOGDIR/$SYSCONF.success" ]; then
	    status=0
	elif [ -e "$LOGDIR/$SYSCONF.failure" ]; then
	    # Error code was set by 'rebuild' in the file
	    status=`cat $LOGDIR/$SYSCONF.failure`
	else
	    # Error code known there after
	    status=8
	fi
	#
    else
	# Built is done on the remote machine through an ssh connexion
	nice ssh $HOST.iram.fr \
	    "source $HOME/.bash_profile;  \
	    source set-iram-gag-search-path ${COMPILER} &&  \
	    ${gagadmdir}/rebuild-mopsic $BUILDOPT $GAG_TAG"
	#
	status=$?
	#
    fi
    #
    case $status in
	0) mybuild_message "Success" ;;
	1) mybuild_message "Problem in calling sequence / options" ;;
	2) mybuild_message "Could not define system" ;;
	3) mybuild_message "Tree problem, e.g. file or directory not found" ;;
	4) mybuild_message "CVS failure" ;;
	5) mybuild_message "Compilation failure (make)" ;;
	6) mybuild_message "Installation failure (make install)" ;;
	7) mybuild_message "Problem when releasing binaries" ;;
	8) mybuild_message "Pre-built version not available" ;;
	*) mybuild_message "Failure (unknown status $status)"
    esac
    return $status
}
#
###########################################################################
#
# Start work by tracking time.
#
date > $LOGFILE
echo >> $LOGFILE
#
###########################################################################
#
# Option parsing
#
temp=`getopt "bf:lhv" "$@"`
if [ $? -ne 0 ]; then usage; exit 1; fi
eval set -- "$temp"
unset temp
while [ $1 != -- ]; do
    case "$1" in
    -b) mkbranch=1 ;;
    -f) SYSFILE=$2; shift ;;  # $SYSFILE is overridden by the input one
    -l) localbuild=1 ;;
    -v) showversion; exit 0 ;;
    -h) usage; exit 0 ;;
    *) usage; exit 1 ;;
    esac
    shift # Next flag
done
shift # Skip double dash
case $1 in
    month) IN_VERSION=month; make_month=1 ;;
    *) IN_VERSION=$1
esac
set abc; shift # This line to avoid remanence effect in a portable way
#
###########################################################################
#
# Translate the input version (set $GAG_TAG)
source $gagadmdir/define-version.sh
gagdefver $IN_VERSION  || error_exit "Defining calling 'gagdefver'"
unset gagdefver GAG_VERS SRCDIR EXEDIR LOGDIR
#
LOGDIR=$MOPSICDIR/logs/$GAG_TAG
if [ ! -d $LOGDIR ]; then
    mkdir -p $LOGDIR || error_exit "creating \$LOGDIR=$LOGDIR directory"
fi
#
# Find the local system, needed in local build mode:
if [ "$localbuild" ]; then
    source $gagadmdir/define-system.sh  # Load gagdefsys function
    gagdefsys || message "Error calling 'gagdefsys' in $PROGNAME"
    LOCAL_EXEC_SYSTEM=$GAG_MACHINE-$GAG_TARGET_VERS
    message "Local builds on $LOCAL_EXEC_SYSTEM."
    unset gagdefsys
    unset GAG_COMP_SYSTEM GAG_EXEC_SYSTEM
    unset GAG_MACHINE GAG_CONFIG
    unset GAG_ENV_KIND GAG_ENV_VERS
    unset GAG_TARGET_KIND GAG_TARGET_VERS
    unset GAG_COMPILER_CKIND GAG_COMPILER_CEXE
    unset GAG_COMPILER_FKIND GAG_COMPILER_FEXE
    # Unset LOGFILE used for reports, it will be filled by another
    # call to rebuild-mopsic-iram.
    unset LOGFILE
fi
#
###########################################################################
#
# Tagging and branching
#
# Need repository write access:
export CVSROOT=:pserver:$MANAGER@netsrv1.iram.fr:/CVS/GILDAS
#
# Tags current version of the main trunk. "day" is the tag used to build
# exactly the same version of the soft on different machines.
# -F is to deplace the "day" tag from its last position to the current
# one.
#
# Make branch named mmmyy and starting at HEAD
#
if [ "$make_month" -a "$mkbranch" ]; then
    message "Create monthly branch $GAG_TAG"
    cvs rtag -r HEAD -b $GAG_TAG $MODULE || error_exit "Creating $GAG_TAG branch"
    nomore=1
fi
#
# Back to repository read-only access:
export CVSROOT=:pserver:anonymous@netsrv1.iram.fr:/CVS/GILDAS
#
# Rebuild-mopsic-iram stops after moving/setting the CVS branchs/tags
# (option -b):
if [ -n "$nomore" ]; then
    message "Success. Call $PROGNAME again to effectively build the version."
    exit 0
fi
#
###########################################################################
#
# Does the real job
#
mybuild_all
#
###########################################################################
#
# Analyze results
#
# Local build case (rebuild-mopsic-iram -l). Check and exit.
if [ -n "$localbuild" ]; then
    if [ -n "$failure" ]; then
	message "Local build FAILURE for $LOCAL_EXEC_SYSTEM."
	exit 99
    else
	message "Local build SUCCESS for $LOCAL_EXEC_SYSTEM."
	exit 0
    fi
fi
#
# Else complete check
if [ -n "$failure" ]; then
    #
    message "Failed to build '$IN_VERSION' version"
    #
else
    #
    if [ "$make_month" ]; then
	monthname=`date -d "3 month ago" "+%b%y" | tr '[:upper:]' '[:lower:]'`
	remove_version $monthname  # Remove 3-month-old version
    fi
    message "Successfully built '$IN_VERSION' version"
    #
fi
#
###########################################################################
#
# Report
#
if [ -n "$failure" ]; then
    report "Failure"
else
    report "Success"
fi
#
###########################################################################
