#!/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

sudo apt-get -qq update

# install required packages
make install-deps

sudo apt-get -y install dpkg-dev debootstrap

if [ ! -e /usr/share/debootstrap/scripts/stretch ]; then
    # workaround for old debootstrap in Trusty
    sudo ln -s sid /usr/share/debootstrap/scripts/stretch
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

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
