#!/bin/sh

NCPUS=`getconf _NPROCESSORS_ONLN`
if test "$NCPUS" != ""; then
  THREADS=-j${NCPUS}
fi

# Queries:
echo -n "Updated build in version.h and changelog (y)? "
read reply
if test ${reply} != "y"; then
  exit 1
fi
echo -n "Updated month and year in manual (y)? "
read reply
if test ${reply} != "y"; then
  exit 1
fi

# Pull from server:
git checkout master || exit $?
git pull --rebase  || exit $?

# Run VALGRIND tests:
TARG_CC=gcc TARG_OBJDIR=x86_64-linux/ make clean || exit $?
TARG_CC=gcc TARG_OBJDIR=x86_64-linux/ make ${THREADS} || exit $?
TARG_CC=gcc TARG_OBJDIR=x86_64-linux/ VALGRIND=1 make test >log 2>&1 || exit $?
NUM_ERRORS=`cat log | grep SUMMARY | grep ERROR | grep -v " 0 errors" | wc -l`
if test ${NUM_ERRORS} -ne 0; then
  echo "${NUM_ERRORS} Valgrind failure(s), see log"
  exit 1
fi
rm -f log

# Run & test x86-64 ASAN,
# i686 cross build (32 bits), i686 ASAN cross build (32 bits),
# PPC(64) cross build (big endian host),
# M68K cross build (M68K 96/80 bit float),
# HPPA cross build,
# S390X cross build,
# Win32 cross builds:
for TARG_OBJDIR in x86_64-linux-asan/ i686-linux/ i686-linux-asan/ ppc-linux/ ppc64-linux/ m68k-linux/ hppa-linux/ s390x-linux/ i686-w32/ x86_64-w64/; do
 TARG_OBJDIR=${TARG_OBJDIR} make clean || exit $?
 TARG_OBJDIR=${TARG_OBJDIR} make ${THREADS} test || exit $?
done

# Run with CLANG, G++, CLANG++, and TCC as target compiler:
for TARG_CC in clang g++ clang++ tcc; do
 TARG_CC=${TARG_CC} TARG_OBJDIR=x86_64-linux/ make clean || exit $?
 TARG_CC=${TARG_CC} TARG_OBJDIR=x86_64-linux/ make ${THREADS} test || exit $?
done

# Build Win32 version
TARG_OBJDIR=i686-w32/ make clean || exit $?
TARG_OBJDIR=i686-w32/ make ${THREADS} test || exit $?
TARG_OBJDIR=i686-w32/ make docs || exit $?
TARG_OBJDIR=i686-w32/ VERSION=curr make bindist-zip || exit $?
mv asl-curr-bin.zip aswcurr.zip

# Build source archive:
make clean || exit $?
make ${THREADS} test docs || exit $?
VERSION=current make distrib || exit $?

# Helper archives:
make archive || exit $?
make zarchive || exit $?

# Manual work:
echo "--> Win32 version in aswcurr.zip."
echo "--> Sources version in asl-current.tar.gz."
echo "--> Build DOS version from asport.zip!"
echo "--> Test VAX version from asport.tar.gz!"
echo "--> set GIT tag and push!"
echo "--> upload archives and release!"
echo "--> push master to John!"
