#!/bin/sh

email()
{
    echo "From: xrockai@fi.muni.cz"
    echo "To: $address"
    echo "Subject: ${failsubj}DIVINE daily $today: $patches"
    echo
    echo '# new patches'
    echo
    cat doc/ci.changes.txt
    echo '# test results'
    echo
    cat doc/ci.test_nohtml.txt
}

set -xe
umask 0022

address=$1
upstream=$2
downstream=$3
today=$(date +%Y-%m-%d)
failsubj=
err=0

# anything new?
darcs pull --dry -a --match 'not name XXX' --no-deps -s --no-set-default $upstream 2>&1 | \
    egrep -v '^Would|^Making|^No remote' | tee changes.txt

if ! grep -q ^patch changes.txt; then exit 0; fi

patchcount=$(grep -c ^patch changes.txt)
if test $patchcount -eq 1; then patches="1 new patch"; else patches="$patchcount new patches"; fi

darcs pull --quiet -a --match 'not name XXX' --no-deps --no-set-default $upstream
gib -c semidbg 'make outdir symlink'
find _build.current/_log/ _build.current/_failed -name \*.txt -exec rm -f {} + # kill old logs

if gib -c semidbg check; then
    darcs push --quiet -a --no-set-default $downstream
else
    err=1
fi

rm -rf _build.current/doc/log
ls -hld _build.current/_log
cp -R _build.current/_log _build.current/doc/log
ls -hld _build.current/doc/log

perl releng/darcs2mu.pl < changes.txt > doc/ci.changes.txt
perl releng/report.pl

gib -c semidbg doc/index.html
exit $err
