#!/usr/bin/env bash
#
# Author: Gerwin Klein, TU Muenchen
#
# DESCRIPTION: Build distribution and run isatest-make for lots of platforms.

## global settings
. "$HOME/hg-isabelle/Admin/isatest/isatest-settings"

TMP=/tmp/isatest-makedist.$$
MAIL=$HOME/bin/pmail

MAKEALL=$HOME/bin/isatest-makeall
TAR=tar

SSH="ssh -f"

export THIS_IS_ISATEST_MAKEDIST=true


## diagnostics

PRG="$(basename "$0")"

function usage()
{
  echo
  echo "Usage: $PRG"
  echo
  echo "   Build distribution and run isatest-make for lots of platforms."
  echo
  exit 1
}

function fail()
{
  echo "$1" >&2
  exit 2
}


## main

# cleanup old error log and test-still-running files
rm -f $ERRORLOG
rm -f $ERRORDIR/isatest-*.log
rm -f $RUNNING/*.runnning

export DISTPREFIX

DATE=$(date "+%Y-%m-%d")
DISTLOG=$LOGPREFIX/isatest-makedist-$DATE.log

echo ------------------- preparing test release --- `date` --- $HOSTNAME > $DISTLOG 2>&1

echo "### cleaning up old dist directory"  >> $DISTLOG 2>&1
rm -rf $DISTPREFIX >> $DISTLOG 2>&1

echo "### cleaning up old isabelle-* directories" >> $DISTLOG 2>&1
rm -rf $HOME/isabelle-*

echo "### building distribution"  >> $DISTLOG 2>&1
mkdir -p $DISTPREFIX
"$HOME/hg-isabelle/bin/isabelle" makedist >> $DISTLOG 2>&1

if [ $? -ne 0 ]
then
    echo ------------------- DIST BUILD FAILED --- `date` --- $HOSTNAME >> $DISTLOG 2>&1
    ELAPSED=$("$HOME/bin/showtime" "$SECONDS")
    log "dist build FAILED, elapsed time $ELAPSED."

    echo "Could not build isabelle distribution. Log file available at" > $TMP
    echo "$HOSTNAME:$DISTLOG" >> $TMP

    for R in $MAILTO; do
        $MAIL "isabelle dist build failed" $R $TMP
    done

    rm $TMP

    exit 1
fi

cd $DISTPREFIX >> $DISTLOG 2>&1
ISABELLE_DIST=`cat $DISTPREFIX/ISABELLE_DIST`
$TAR xvzf $ISABELLE_DIST >> $DISTLOG 2>&1
ln -sf $(basename $ISABELLE_DIST .tar.gz) Isabelle
cp Isabelle/etc/settings Isabelle/etc/settings.orig

echo ------------------- prepared test successfully --- `date` --- $HOSTNAME >> $DISTLOG 2>&1

ELAPSED=$("$HOME/bin/showtime" "$SECONDS")
log "dist build successful, elapsed time $ELAPSED."


## clean up var/running
rm -f $RUNNING/*
mkdir -p $RUNNING


## spawn test runs

$SSH lxbroy10 "$MAKEALL $HOME/settings/at64-poly"
sleep 15
$SSH lxbroy4 "
  $MAKEALL -l HOL-Library $HOME/settings/at-poly;
  $MAKEALL -l HOL-Library $HOME/settings/at-poly-e;
  $MAKEALL $HOME/settings/at-poly-test"
sleep 15
$SSH lxbroy3 "$MAKEALL -l HOL-Library $HOME/settings/at-sml-dev-e"
sleep 15
$SSH macbroy2 "
  $MAKEALL $HOME/settings/mac-poly64-M4;
  $MAKEALL $HOME/settings/mac-poly64-M8;
  $MAKEALL $HOME/settings/mac-poly-M4;
  $MAKEALL $HOME/settings/mac-poly-M8;
  $MAKEALL $HOME/settings/mac-poly-M8-skip_proofs;
  $MAKEALL $HOME/settings/mac-poly-M8-quick_and_dirty"
sleep 15
$SSH macbroy6 "$MAKEALL $HOME/settings/mac-poly64-M2"
sleep 15
$SSH macbroy30 "$MAKEALL $HOME/settings/mac-poly-M2"

echo ------------------- spawned tests successfully --- `date` --- $HOSTNAME >> $DISTLOG 2>&1

gzip -f $DISTLOG

