#!/bin/sh
#
# robotpkg bulk build script
#

# Process optional arguments
config=/opt/openrobots/etc/rbulk.conf
kill=
while test $# -gt 0; do
    case "$1" in
        -f)	config="$2"; shift 2;;
        -k)	kill=yes; shift;;
        -*)	echo 1>&2 "${0##*/}: unknown option -- ${1#-}"
                exit 1;;
        *)	break;;
    esac
done
case $config in
    /*) ;;
    *) config=/opt/openrobots/etc/$config ;;
esac

. $config

read s r m <<EOF
`. $robotpkg_src/mk/platform/opsys.sh`
EOF

: ${bulk_tag:=$s-$r-$m}


# --- redirect output and errors -------------------------------------

pid=$$
locking=.
bulk_logfile="$bulk_logdir/$bulk_tag.log"
bulk_lock="$bulk_logdir/lock-file"
bulk_status="$bulk_logdir/status"
date_start=`LC_ALL=C date`
umask 22
test -d $bulk_logdir || mkdir -p $bulk_logdir
test -f $bulk_lock || touch $bulk_lock
test -z "$bulk_db" || test -f $bulk_db || touch $bulk_db

# remove lock file and send an e-mail with the log on error
aterror() {
    s=$?
    if test $s -ne 0; then
        {
            echo "From: Robert Bulk <robotpkg@laas.fr>"
            echo "To: $bulk_email"
            echo "Subject: [rbulk-build]" `hostname` "$bulk_target exit $s"
            echo "X-LogFile: $bulk_logfile"
            echo ""
            if test -f "$bulk_logfile"; then
                cat "$bulk_logfile"
            else
                echo "Errors have been logged in the database"
            fi
        } | $sendmail -t
    fi

    # drop dangling log files if it was not done (failure)
    for d in $bulk_logdir/.report $bulk_logdir/*; do
        test -d $d && rm -rf $d
    done
    rm -f $bulk_logfile $bulk_status
    /opt/openrobots/sbin/rbulk-locked $bulk_lock /bin/sh -c "			\
        if test -z '$locking'; then					\
          rm -f $bulk_logdir/RUNNING $bulk_logdir/STOP;			\
        fi"
    trap - 0
    exit $s
}

# catch signal as an error
atsig() {
    exit 128
}

exec 2>&1
trap aterror 0
trap atsig INT
trap atsig QUIT
trap atsig TERM
set -e

test -n "$bulk_target" || { echo 'empty $bulk_target'; exit 2; }

# acquire lock. if killing, STOP
while :; do
  /opt/openrobots/sbin/rbulk-locked $bulk_lock /bin/sh -ec "	\
    if test -f $bulk_logdir/RUNNING; then		\
      test -z '$kill' || echo $pid >$bulk_logdir/STOP;	\
      read rpid < $bulk_logdir/RUNNING;			\
      if kill -0 \"\$rpid\"; then exit 100; fi;		\
    fi;							\
    echo $pid >$bulk_logdir/RUNNING;			\
    test -z '$kill' || rm -f $bulk_logdir/STOP;		\
    exit 0" && break
  w=$?
  if test $w -eq 100; then
      locking=.$locking
      if test ${#locking} -gt 600; then
          echo '*** Timeout acquiring lock'
          exit 2;
      fi
  else
      echo '*** Error acquiring lock'
      exit 2
  fi

  echo '*** Another instance is running. Sleeping for 60s.'
  sleep 60
done
locking=

if test -n "$kill"; then exit 0; fi

if test -n "$robotpkg_subdir"; then
    path="-path $robotpkg_subdir"
fi

export ROBOTPKG_BASE=$bulk_localbase
export MAKECONF=$robotpkg_conf

# clean any previous dandling logs
for d in $bulk_logdir/.report $bulk_logdir/*; do
    test -d $d && rm -rf $d
done
rm -f $bulk_logfile $bulk_status


{ # tee $bulk_logfile: the pipe creates a new process

aterror() { s=$?; test "$s" -eq 0 || echo $s >$bulk_status; }
trap aterror 0
trap atsig INT
trap atsig QUIT
trap atsig TERM

if test -n "$bulk_db"; then
    echo
    echo "--- Syncing bulk database ----------------------------------------"
    echo

    /opt/openrobots/sbin/rbulk-locked $bulk_db /bin/sh -ec "			\
      /opt/openrobots/sbin/rbulk-report runarch $bulk_db $bulk_tag;		\
      /opt/openrobots/sbin/rbulk-report db2html $path $bulk_db $bulk_logdir/.report;\
      $rsync -zaul $bulk_logdir/.report/ $report_url			\
    "
fi

updatedb() {
  aterror

  if test -n "$bulk_db"; then
    echo
    echo "--- Updating bulk database ---------------------------------------"
    echo

    # generate report
    /opt/openrobots/sbin/rbulk-locked $bulk_db /bin/sh -ec "\
      /opt/openrobots/sbin/rbulk-report log2db $path $bulk_logdir $bulk_db;	\
      /opt/openrobots/sbin/rbulk-report db2html				\
        $path $bulk_db $bulk_logdir/.report;				\
      $rsync -zaul --delete $bulk_logdir/.report/ $report_url/;		\
      /opt/openrobots/sbin/rbulk-report db2mail				\
        $path $bulk_db $bulk_tag '$report_email' '$sendmail -t'"
    rm -rf $bulk_logdir/.report
  fi

  date_stop=`LC_ALL=C date`
  echo
  echo "--- Bulk started $date_start"
  echo "--- Bulk stopped $date_stop"
}

trap updatedb 0

echo
echo "--- Updating robotpkg --------------------------------------------"
echo

# pull source tree
echo "Pulling $robotpkg_src/$robotpkg_subdir"
(cd $robotpkg_src/$robotpkg_subdir &&
     $git fetch $robotpkg_pull &&
     $git reset --hard FETCH_HEAD)

# update rbulk
for pkg in $robotpkg_update; do
  echo "Updating $pkg"
  (cd $robotpkg_src/$pkg && $make update)
done

echo
echo "--- Running build for $bulk_target -------------------------------"
echo

# clean bulk_base
test -z "$bulk_base" || (
    mkdir -p "$bulk_base" && cd $bulk_base && find . -delete
)

# bulk set
test ! -f $bulk_logdir/STOP || {
    echo 'Interrupted by' $bulk_logdir/STOP
    exit 2
}

(
    cd $robotpkg_src && time $make $bulk_target				\
        "BULKBASE=$bulk_base" "BULK_LOGDIR=${bulk_logdir}" "tag=$bulk_tag"
)

trap aterror 0
updatedb

} 2>&1 | tee "$bulk_logfile"

test -s "$bulk_status" && exit `cat $bulk_status`
exit 0
