#!/bin/sh

set -e
set -x

repo_name="$(basename $PWD)"
repo_dir="$PWD"

# drop qubes- prefix
repo_name=${repo_name#qubes-}

if [ -n "$1" ]; then
    # Build this component(s) instead, but still use what Travis-CI downloaded
    override_components="$1"
fi

# go to builder main directory
cd "$(dirname $0)/.."

keep_alive() {
    while sleep 300; do
       echo "*** STILL ALIVE ***"
    done
}

# place cachedir outside qubes-builder (to not restore qubes-builder itself
# from Travis-CI cache)
mv cache $HOME/qubes-builder-cache
ln -s $HOME/qubes-builder-cache cache

# use specific builder conf for Travis-CI builds
export BUILDERCONF=scripts/travis-builder.conf

if [ -z "$DISTS_VM" -a -z "$DIST_DOM0" ]; then
    echo "Specify either DISTS_VM or DIST_DOM0 in .travis.yml" >&2
    exit 1
fi

#if [ -z "$USE_QUBES_REPO_VERSION" ]; then
#    echo "Specify target Qubes version with USE_QUBES_REPO_VERSION in .travis.yml" >&2
#    exit 1
#fi

# We don't need MongoDB, so don't care it their key is expired or not
sudo rm -f /etc/apt/sources.list.d/mongodb*

sudo apt-get -qq update

# install required packages
make install-deps

sudo apt-get -y install dpkg-dev debootstrap

if ! getent group mock >/dev/null; then
    # mock require group with this specific name
    sudo groupadd mock
fi

if [ ! -e /usr/share/debootstrap/scripts/stretch ]; then
    # workaround for old debootstrap in Trusty
    sudo ln -s sid /usr/share/debootstrap/scripts/stretch
fi

if [ -L /dev/shm ]; then
    # don't use symlink for /dev/shm, as it will break when bind-mounting /dev
    # into chroot (archlinux)
    sudo rm -f /dev/shm
    sudo mkdir /dev/shm
    sudo mount -t tmpfs shm /dev/shm
fi

# download builder plugins
make get-sources COMPONENTS='$(BUILDER_PLUGINS)'

if [ -n "$override_components" ]; then
    make COMPONENTS="$override_components" get-sources
fi

# place Travis-CI downloaded sources in qubes-src
if [ -d qubes-src/${repo_name} ]; then
    rm -rf qubes-src/${repo_name}
fi
cp -al $repo_dir qubes-src/$repo_name

# install extra packages - after downloading builder plugins and other sources
make install-deps

if [ "0$VERBOSE" -eq 0 ]; then
    # if not showing build log, echo some text to prevent Travis-CI timeout
    keep_alive &
    keep_alive_pid=$!
fi

# download additional sources if needed and compile
if [ -n "$override_components" ]; then
    make COMPONENTS="$override_components" get-sources-extra qubes
else
    make COMPONENTS=$repo_name get-sources-extra qubes
fi

if [ -n "$keep_alive_pid" ]; then
    kill -9 $keep_alive_pid
fi
find qubes-packages-mirror-repo -type f -ls -exec sha1sum {} +
