#!/bin/bash
#
# Variable and function definitions
#
AUTHOR='J. Pety <pety@iram.fr>'
VERSION=`echo '$Revision: 1.17 $' | cut -d' ' -f2`
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-www             # As known by CVS
#
WORKDIR=$GILDAS_HOME/gildas/$MODULE
INSTALLDIR=$GILDAS_HOME/www/GILDAS
INSTALLFIL="*.html *.css images memos misc"
gagadmdir=$GILDAS_HOME/gildas/gildas-admin
REPORTFILE=$GILDAS_HOME/gildas/logs/rebuild-www.txt
#
# Mail report
RECIPIENTS="pety bardeau reynier"
MAILHEADER="[gildas-www-compilation]"
#
########################################################################
#
# Program general functions
#
function showversion() {
    echo "$PROGNAME version $VERSION, by $AUTHOR"
    echo "Project: $PROJECT"
}
#
function message() {
    echo `date "+%F %T"` "$PROGNAME: $1"
}
#
function error_exit() {
    #
    # Write message to STDOUT
    message ""
    message "$PROGNAME error: $1"
    message ""
    #
    # Write message to report file
    echo "$PROGNAME error: $1" >> $REPORTFILE
    #
    # Mail report
    report "Failure"
    exit 1
    #
}
#
function report() {
    #
    # Finalize report file with date
    echo >> $REPORTFILE
    date >> $REPORTFILE
    #
    SUBJECT="$MAILHEADER $1"
    #
    message "Sending report"
    message "File =       $REPORTFILE"
    message "Subject =    $SUBJECT"
    #
    if [ -n "$RECIPIENTS" ]; then
	message "Recipients = $RECIPIENTS"
	cat $REPORTFILE | $gagadmdir/sendmail.pl -s "$SUBJECT" $RECIPIENTS
    else
	message "Recipients = <none>"
    fi
    #
}
#
function usage() {
    cat <<EOF 1>&2

This script is used to update and rebuild Gildas web page:
  - html sources are updated from CVS repository,
  - other documents (e.g. html and pdf of each Gildas program) are
    copied from latest successfull Gildas built.

An abbreviated log is sent to the GILDAS maintainers.

usage: $PROGNAME

You must have permissions to write on the http server.

EOF
}
#
function task-list-html() {
    INSTALLTASKDIR=$INSTALLDIR/doc/tasks
    TASKLISTHTML=$INSTALLDIR/doc/tasks/task-list.html

    echo "<html>" >> $TASKLISTHTML
    echo "<body>" >> $TASKLISTHTML
    for x in `ls $INSTALLTASKDIR/*-task-list.hlp`; do
        while read line; do
          if [[ $line =~ "1 ".* ]]; then
              # Suppress the leading "1 ", uppercase
              echo "${line#1 }<BR>" | tr '[:lower:]' '[:upper:]' >> $TASKLISTHTML
          elif [ -n "$line" ]; then
              # Get task name:
              taskname=${line%% *}  # Operator %% deletes the longest possible match for " *" to the right
              ltaskname=`echo $taskname | tr '[:upper:]' '[:lower:]'`  # lowercase
              comment=${line#* }    # Operator # deletes the shortest possible match for "* " to the left
              echo "<a href=${ltaskname}.hlp>${taskname}</a>$comment<BR>" >> $TASKLISTHTML
          else
              # Blank line
              echo "<BR>" >> $TASKLISTHTML
          fi
        done < $x
    done
    echo "</body>" >> $TASKLISTHTML
    echo "</html>" >> $TASKLISTHTML

}
#
###########################################################################
#
# Source .bash_profile to ensure a correct definition of the PATH.
# (In particular the PATH toward the cvsrelease script)
#
# source $HOME/.bash_profile
#
# Following line to enable authentication by pubkey
#
# chmod go=rx $HOME
#
###########################################################################
#
# Start work by tracking time
#
date > $REPORTFILE
echo >> $REPORTFILE
#
###########################################################################
#
# Does the real job
#
#
# Define $LOGFILE (in current day log directory)
source $gagadmdir/define-version.sh
gagdefver day || \
    error_exit "Could not define define version as 'day'"
if [ ! -d $LOGDIR ]; then
    mkdir -p $LOGDIR || error_exit "creating \$LOGDIR directory"
fi
LOGFILE=$LOGDIR/rebuild-www
#
#
# Define $SRCDIR and $EXEDIR (use last successfull build)
gagdefver last || \
    error_exit "Could not define define version as 'last'"
unset gagdefver
#
# Define $GAG_EXEC_SYSTEM
source $gagadmdir/define-system.sh
gagdefsys || \
    error_exit "Could not define define system"
unset gagdefsys
#
#
message "Going to $WORKDIR"
cd $WORKDIR > $LOGFILE.env 2>&1 || \
    error_exit "Going to $WORKDIR"
#
#
message "Cleaning compilation directory"
make distclean > $LOGFILE.clean 2>&1 || \
    error_exit "Make-ing distclean"
#
#
message "Updating html sources from CVS"
cvs -q up -A > $LOGFILE.cvs 2>&1 || \
    error_exit "Updating html sources from CVS"
#
#
message "Creating NEWS.tex from Gildas sources"
echo "\begin{verbatim}" >  NEWS.tex
cat $SRCDIR/NEWS        >> NEWS.tex
echo "\end{verbatim}"   >> NEWS.tex
#
#
message "Creating doc/txt/ONEWS"
if [ ! -d "$EXEDIR/doc/txt" ] ; then
    mkdir -pv $EXEDIR/doc/txt > $LOGFILE.install 2>&1 || \
	error_exit "Mkdir-ing $EXEDIR/doc/txt"
fi
# Force copy as $EXEDIR/doc/txt/ONEWS may already exist (e.g. several
# run in the same day)
cp -fv $SRCDIR/ONEWS $EXEDIR/doc/txt/ >> $LOGFILE.install 2>&1 || \
        error_exit "Copying $SRCDIR/ONEWS to $EXEDIR/doc/txt"
#
#
message "Compiling"
# Note that (ht)latex gives a prompt in case of error. Redirect STDIN
# to /dev/null (the effect is similar to CTRL-D when the prompt waits
# for an input). Unfortunately, the error status is lost by htlatex
# (see below)
make html < /dev/null > $LOGFILE.compile 2>&1 || \
    error_exit "make-ing html"
#
# Check for compilation errors. NB: we could parse the word "Error"
# but this is a bit too generic. Parse "Emergency stop" which is issued
# by the above CTRL-D in case of error.
if [ `grep -c "Emergency stop" $LOGFILE.compile` -ge 1 ]; then
  error_exit "make-ing html"
fi
#
# Installation
message "Installing"
# Clean destination directory first
(cd $INSTALLDIR && rm -rf $INSTALLFIL) >> $LOGFILE.clean 2>&1 || \
    error_exit "Make-ing install-clean"
cp -pru $INSTALLFIL $INSTALLDIR >> $LOGFILE.install 2>&1 || \
    error_exit "make-ing install-html"

# Copy the full documentation directory. It needs special user
# rights: we make a copy to avoid degrading access to standard gildas
# installation directories (e.g. gildas-exe-last/doc)
rm -rf $INSTALLDIR/doc >> $LOGFILE.clean 2>&1

echo "Running command: cp -r $EXEDIR/doc $INSTALLDIR/doc" >> $LOGFILE.install
cp -r $EXEDIR/doc $INSTALLDIR/doc >> $LOGFILE.install 2>&1 || \
    error_exit "Linking $INSTALLDIR/doc to $EXEDIR/doc"
echo "Success at "`date +"%H:%M:%S.%N"` >> $LOGFILE.install

# Special case for tasks: task lists and hlp are in
# $EXEDIR/$GAG_EXEC_SYSTEM/tasks
echo "Running command: cp $EXEDIR/$GAG_EXEC_SYSTEM/tasks/*.hlp $INSTALLDIR/doc/tasks" >> $LOGFILE.install
cp $EXEDIR/$GAG_EXEC_SYSTEM/tasks/*.hlp $INSTALLDIR/doc/tasks >> $LOGFILE.install 2>&1 || \
    error_exit "Copying $EXEDIR/$GAG_EXEC_SYSTEM/tasks/*.hlp into $INSTALLDIR/doc/tasks"
echo "Success at "`date +"%H:%M:%S.%N"` >> $LOGFILE.install

# Generate task-list.html
task-list-html >> $LOGFILE.install

# Post-install: deal with group and permissions
echo "Running command: chgrp -R web $INSTALLDIR" >> $LOGFILE.install
chgrp -R web $INSTALLDIR >> $LOGFILE.install 2>&1 || \
    error_exit "chgrp-ing web $INSTALLDIR"
echo "Success at "`date +"%H:%M:%S.%N"` >> $LOGFILE.install

# Directories and files need specific access mode for the web server
# (in particular no access to "others" for security reasons)
echo "Running command: chmod -R \"u=rwX,g=rX,o=\" $INSTALLDIR" >> $LOGFILE.install
chmod -R "u=rwX,g=rX,o=" $INSTALLDIR >> $LOGFILE.install 2>&1 || \
    error_exit "chmod-ing $INSTALLDIR"
echo "Success at "`date +"%H:%M:%S.%N"` >> $LOGFILE.install
#
###########################################################################
#
# Report
#
echo "Recompiling www sources was a success" >> $REPORTFILE
report "Success"
#
###########################################################################
