#!/usr/bin/env bash

set -x --

SUDO=
APT_GET=$(which apt-get)
APT_FLAGS='-q --no-install-suggests --no-install-recommends'
PIP=$(which pip)
PIP_FLAGS='--no-binary :all'

DEPENDS="build-essential openssl sqlite3 python3-dev python3-setuptools gettext"
DEPENDS="${DEPENDS} libgeoip-dev tor-geoipdb libjpeg-dev"
HERE=$(dirname $0)

if [ "$EUID" != "0" ] ; then SUDO=$(which sudo); fi
# pip is pre-installed on Travis-CI machines in their Python environment, so
# we should avoid reinstalling it (as that might do odd things to the
# virtualenv that we're already inside):
if [ "$TRAVIS" == "true" ] ; then
    DEPENDS="${DEPENDS} realpath"
else
    DEPENDS="${DEPENDS} python3-pip flog"
fi

if [ "$CI" == "true" ] ; then
    APT_FLAGS="-y ${APT_FLAGS}"
fi
    
MISSING=""
for dep in $DEPENDS ; do
    if ! test "$(dpkg -l $dep | grep \"ii  $dep\")" ; then
        MISSING="${MISSING} $dep"
    fi
done

$SUDO $APT_GET install ${APT_FLAGS} ${MISSING}

# When running on Travis, we are installing a few extra packages, e.g., to
# determine code coverage.
if [ "$TRAVIS" == "true" ] ; then
    $PIP install $PIP_FLAGS -r "$HERE/../.travis.requirements.txt"
else
    $PIP install $PIP_FLAGS -r "$HERE/../requirements.txt"
fi
