#!/bin/bash -e
# Build script wrapper
#
# How to use:
#
# * Build package only in temporary location _tmpRoot,
#   use it also for storing of temporary files (which should be
#   removed before creating the package). The directory is deleted
#   at the end of the script. By using it that way, no garbage files
#   are left over after building and symlink attacks on temporary
#   directories are prevented.
#
#   The script will place the new packages in the current working
#   directory, overwriting any existing files of same name.

if [ "${EUID} ${UID}" = "0 0" ] && touch /fake-root-detect 2> /dev/null; then
  rm /fake-root-detect
  echo "Build should not be run as root!" >&2
  exit 1
fi

# Export tmp dir to allow large package builds within vservers
export TMPDIR="/var/tmp"
_projectDir="$(pwd)"

# Use a temporary directory for building, no need to keep it.
_tmpRoot="$(mktemp -d)"
echo "Building package at ${_tmpRoot}" >&2

_debDirectory="${_tmpRoot}/deb-build"
_tarVersion=$(head -1  debian/changelog | awk 'match($0, /\(.*\)/) {
    print substr($0, RSTART+1, RLENGTH-4)
}
')
mkdir -- "${_debDirectory}"
cp -a -- "${_projectDir}/debian" "${_projectDir}/source/root" "${_debDirectory}"
cp -a -- "${_projectDir}/README.md" "${_debDirectory}"
fakeroot -- tar -C ${_debDirectory} -czf "${_tmpRoot}/logdata-anomaly-miner_${_tarVersion}.orig.tar.gz" --transform 's,^./,deb-build/,' .
gpg -ab "${_tmpRoot}/logdata-anomaly-miner_${_tarVersion}.orig.tar.gz"

# Build packages:
# -F: full build
# -us: unsigned sorce
# -uc: unsigned changes
# -sa: force inclusion of original source
(set -e; cd -- "${_debDirectory}"; dpkg-buildpackage -S -us -uc -sa; dpkg-buildpackage -b -uc)
rm -rf -- "${_debDirectory}"
cp -a -- "${_tmpRoot}/logdata-anomaly-miner_"* .
rm -rf -- "${_tmpRoot}"

# Build the alienated package for CentOS/Redhat.
_debFileName="$(ls -- logdata-anomaly-miner_*_all.deb)"
_debVersion="$(echo "${_debFileName}" | sed -r -e 's/logdata-anomaly-miner_([0-9a-z.~-]+)_all.deb/\1/')"
fakeroot -- /usr/bin/alien --to-rpm "${_debFileName}"
mv -i -- "logdata-anomaly-miner-${_debVersion}-2.noarch.rpm" "logdata-anomaly-miner-${_debVersion}-2.noarch.alien.rpm" < /dev/null

echo "Build successful" >&2
