#!/bin/bash

PATH=/home/`whoami`/.local/bin:$PATH

# Stop on error
set -e
# Echo all commands to Travis log
set -x

mkdir build-travis build32 build-sparse

# Build with latest clang first
cd build-travis
CC=clang-7 CFLAGS=-Werror cmake -GNinja .. -DIOCTL_MODE=both -DENABLE_STATIC=1
ninja
../buildlib/check-build --src .. --cc clang-7

# 32 bit build to check format strings/etc
cd ../build32
# travis is not configured in a way that enables all 32 bit
# packages. We could fix this with some sudo stuff.. For now turn off libnl
CC=gcc-8 CFLAGS="-Werror -m32 -msse3" cmake -GNinja .. -DENABLE_RESOLVE_NEIGH=0 -DIOCTL_MODE=both -DNO_PYVERBS=1
ninja

# Run sparse on the subdirectories which are sparse clean
cd ../build-sparse
mv ../CMakeLists.txt ../CMakeLists-orig.txt
grep -v "# NO SPARSE" ../CMakeLists-orig.txt > ../CMakeLists.txt
CC=cgcc CFLAGS="-Werror" cmake -GNinja .. -DIOCTL_MODE=both -DNO_PYVERBS=1
ninja | grep -v '^\[' | tee out
# sparse does not fail gcc on messages
if [ -s out ]; then
   false
fi
mv ../CMakeLists-orig.txt ../CMakeLists.txt

# Test with coherent DMA mode disabled (ie as would be on ARM32, etc)
cd ../build-travis
cp ../util/udma_barrier.h ../util/udma_barrier.h.old
echo "#error Fail" >> ../util/udma_barrier.h
rm CMakeCache.txt
CC=clang-7 CFLAGS=-Werror cmake -GNinja .. -DIOCTL_MODE=both
ninja
cp ../util/udma_barrier.h.old ../util/udma_barrier.h

# Finally run through gcc-8 64 bit through the debian packaging This gives a
# good clue if patches are changing packaging related things, the RPM stuff
# will have to be audited by hand.

# When running cmake through debian/rules it is hard to set -Werror,
# instead force it on by changing the CMakeLists.txt
cd ..
echo 'set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Werror")' >> buildlib/RDMA_EnableCStd.cmake
sed -i -e 's/-DCMAKE_BUILD_TYPE=Release/-DCMAKE_BUILD_TYPE=Debug/g' debian/rules
sed -i -e 's/ninja \(.*\)-v/ninja \1/g' debian/rules

CC=gcc-8 debian/rules build
fakeroot debian/rules binary
