#!/bin/bash
#
# Variable and function definitions
#
AUTHOR='J. Pety <pety@iram.fr>'
PROJECT='GILDAS <http://www.iram.fr/IRAMFR/GILDAS>'
PROGNAME=`basename $0`
#
# Administration
GILDAS_USER=gildas            # ID used to connect to computers
GILDAS_HOME=/users/softs/gildas
MODULE=gildas                 # As known by CVS
#
WORKDIR=$GILDAS_HOME/off-line
LOGFILE=$WORKDIR/logs/rebuild-bure.txt
SYSFILE=rebuild-bure.systems  # Default file where systems are read from
PENDINGFILE=$WORKDIR/to_be_removed.txt # File where versions to be removed are stored
#
# Mail reports
RECIPIENTS="pety bardeau reynier"
MAILHEADER="[pdbi-offline-compilation]"
#
###########################################################################
#
# Ensure a stable $gagadmdir to start the process
#
export gagadmdir=$WORKDIR/gildas-admin
#
###########################################################################
#
# Load global functions
#
source $gagadmdir/rebuild-commons
#
###########################################################################
#
# Define local functions
#
function usage() {
    cat <<EOF 1>&2

Script used:
  1. To rebuild every night the development version of GILDAS on all
     systems available at BURE. When compilation on all systems is a
     success, tags the version as "last" (for last fully compilable
     version);
  2. To build every month the monthly version on all systems
     available at BURE.
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
as described in the "rebuild-bure.cron" file.

usage: $PROGNAME version

version:
  dev
  day
  month

options:
  -f         Force release even with a failure. Use with extreme care,
             probably only with a timeout error.
  -s <file>  Use $gagadmdir/<file> instead of $gagadmdir/$SYSFILE as systems file
  -R         Remove current version before building new ones
  -h         Show this help page
  -v         Show version information

EOF
}
#
function mybuild() {               # Examples:
    #
    unset BUILDKIND HOST EXEC_SYSTEM SYSTEM CONFIG TARGET
    #
    BUILDKIND=$1                   # exe
    HOST=$2                        # pctcp30.iram.fr
    EXEC_SYSTEM=$3                 # x86_64-fedora6
    SYSTEM=$3-$4                   # x86_64-fedora6-ifort
    COMPILER=$4                    # ifort
    if [ -n "$5" ]; then
      # Support syntax like o:myconfig or t:mytarget
      opt=`echo $5 | cut --delimiter=: --fields=1`
      if [ $opt = "o" ]; then
        CONFIG=`echo $5 | cut --delimiter=: --fields=2`
      elif [ $opt = "t" ]; then
        TARGET=`echo $5 | cut --delimiter=: --fields=2`
      fi
    fi
    #
    if [ -z "$CONFIG" ]; then
	SYSCONF=$SYSTEM            # x86_64-fedora6-ifort
    else
	SYSCONF="$SYSTEM-$CONFIG"  # x86_64-fedora6-ifort-staticlink
    fi
    case $BUILDKIND in
	all) if [ "$IN_VERSION" = "dev" ]; then BUILDOPT="$RMOPT -CIPW"; else BUILDOPT="$RMOPT -a"; fi ;;  # No cvs up for dev version
	exe) if [ "$IN_VERSION" = "dev" ]; then BUILDOPT="$RMOPT -CI";   else BUILDOPT="$RMOPT -e"; fi ;;  # No cvs up for dev version
	*) echo "${SYSCONF}: ${BUILDKIND} is an unrecognized kind of build" >> $LOGFILE ; return 255
    esac
    if [ -n "$CONFIG" ]; then
       BUILDOPT="$BUILDOPT -o $CONFIG"
    fi
    if [ -n "$TARGET" ]; then
       BUILDOPT="$BUILDOPT -t $TARGET"
    fi
    message "Connecting $HOST as user $GILDAS_USER..."
    nice ssh $GILDAS_USER@$HOST  \
        "source .bash_profile; export GAG_ADDONS=yes; source set-bure-paths ${COMPILER} && \
        ${gagadmdir}/rebuild ${BUILDOPT} -c ${COMPILER} ${IN_VERSION}"
    status=$?
    case $status in
	0) mybuild_message "Success" ;;
	1) mybuild_message "Wrong build options" ;;
	2) mybuild_message "Failure in system definition" ;;
	3) mybuild_message "Failure in directory preparation" ;;
	4) mybuild_message "Failure in removing old version" ;;
	5) mybuild_message "Failure in check-out" ;;
	6) mybuild_message "Failure in environment setting" ;;
	7) mybuild_message "Failure in compilation" ;;
	8) mybuild_message "Failure in installation" ;;
	9) mybuild_message "Failure in PDF doc compilation or installation" ;;
       10) mybuild_message "Failure in HTML doc compilation or installation" ;;
	*) mybuild_message "${status} is an unrecognized exit status"
    esac
    return $status
}
#
###########################################################################
#
# Start work by tracking time.
#
date > $LOGFILE
echo >> $LOGFILE
#
###########################################################################
#
# Option parsing
#
temp=`getopt "fs:Rhv" "$@"`
if [ $? -ne 0 ]; then usage; exit 1; fi
eval set -- "$temp"
unset temp
while [ $1 != -- ]; do
    case "$1" in
    -f) force=1 ;;
    -s) SYSFILE=$2; shift ;;  # $SYSFILE is overridden by the input one
    -R) remove=1 ;;
    -v) showversion; exit 0 ;;
    -h) usage; exit 0 ;;
    *) usage; exit 1 ;;
    esac
    shift # Next flag
done
shift # Skip double dash
#
case $1 in
    dev)   IN_VERSION=dev ;;
    day)   IN_VERSION=day;   make_day=1 ;;
    month) IN_VERSION=month; make_month=1 ;;
    *) error_exit "$1 version not supported"
esac
set abc; shift # This line to avoid remanence effect in a portable way
#
# Leave the choice between removing everything to start from clean state
# and just updating to save lot's of time.
#
if [ "$remove" ]; then
    RMOPT="-D "   # Only a 'make distclean' will be performed
else
    RMOPT=
fi
#
###########################################################################
#
# Source .bash_profile to ensure a correct definition of the PATH.
# (In particular the PATH toward the cvsrelease script)
#
# source $HOME/.bash_profile
#
# Source GILDAS related definitions at bure
#
# source $gagadmdir/gildas-bure-def.sh
#
# Following line to enable authentication by pubkey
#
# chmod go=rx $HOME
#
# Repository read-only access
# export CVSROOT=:pserver:anonymous@cvs.iram.fr:/CVS/GILDAS # ZZZ
#
###########################################################################
#
# First clean pending versions to be removed
#
cd $WORKDIR
#
clean_pending
#
###########################################################################
#
# Does the real job. Build on a single kind of system available at Bure
#
mybuild_all
#
###########################################################################
#
# Analyze results
#
if [ -n "$failure" ] && [ -z "$force" ]; then
    # Build was a failure and -f was not invoked => global build failure
    #
    if [ -n "$make_day" ]; then
	day_failure
	#
    else
	message "Failed to build '$IN_VERSION' version"
    fi
    #
else
    # Build was a success, or a failure but -f was invoked => global build
    # success
    #
    if [ -n "$make_day" ]; then
	day_success 4  # Keep 4 daily versions
	#
    elif [ -n "$make_month" ]; then
	month_success
	#
    else
	message "Successfully built '$IN_VERSION' version"
    fi
    #
fi
#
###########################################################################
#
# Report
#
if [ -n "$failure" ]; then
    report "Failure"
else
    report "Success"
fi
#
###########################################################################
