#!/bin/bash
#
# This script is for deploying the staging server.
#
set -eETxv --
echo $-

# If `true`, do `python setup.py install` on the untarred packages listed in
# the `$DEPS` variable below:
INSTALL_DEPS=false

# If `true`, remove the old `bridges-test` virtualenv and recreate it:
CREATE_NEW_VENV=true

. /srv/bridges.torproject.org/etc/environment-staging

export PYTHONPATH
export PIP_CONFIG_FILE

if $CREATE_NEW_VENV ; then
    # If we're supposed to recreate the venv, delete it first.
    if test -d "$VIRTUALENV"; then rm -rf "$VIRTUALENV"; fi
    if ! test -x "$VIRTUALENV_ACTIVATE"; then
        python3 -m venv "$VIRTUALENV"
    fi
fi

# Enter the virtual environment.
source $VIRTUALENV_ACTIVATE

# Install our requirements with the venv pip in order to avoid using
# easy_install:
if $CREATE_NEW_VENV ; then
    pip3 install wheel
    cd $BRIDGEDB_SOURCE_REPO && $(which pip3) install -r requirements.txt
fi

# Install BridgeDB from our local copy of https://git.torproject.org/bridgedb.git
cd $BRIDGEDB_SOURCE_REPO && make reinstall

# Copy the descriptor files
for fname in $STATUS_FILE $BRIDGE_FILES $EXTRA_INFO_FILES ; do
    if [ -e "$fname" ] ; then
        mkdir -p "$FROM_AUTH"
        newfile="$FROM_AUTH"/${fname##$(dirname $fname)/}
        printf "Copying ${fname} to ${newfile}...\n"
        cp "$fname" "$newfile"
    fi
done

! test -e "$BRIDGEDB_PIDFILE" || ( kill `cat "$BRIDGEDB_PIDFILE"` && sleep 2 )

"$BIN_DIR"/run-bridgedb-staging
exit $?
