#!/bin/sh -e

# NOTE: this script is meant to be ran by the 'rattail' user!

if [ "$1" = "--verbose" ]; then
    VERBOSE='--verbose'
    QUIET=
else
    VERBOSE=
    QUIET='--quiet'
fi

% if not production:
SRC=${envroot}/src
% endif
PIP=${envroot}/bin/pip
export PIP_CONFIG_FILE=${envroot}/pip.conf

# upgrade pip
$PIP install $QUIET --disable-pip-version-check --upgrade pip wheel

% if not production:
# now we fetch latest source code and install any "new" dependencies...

# rattail
cd $SRC/rattail
git pull $QUIET
find . -name '*.pyc' -delete
$PIP install $QUIET --editable .

# tailbone
cd $SRC/tailbone
git pull $QUIET
find . -name '*.pyc' -delete
$PIP install $QUIET --editable .

## begin corepos
% if env.theo_integrates_with == 'corepos':

# pycorepos
cd $SRC/pycorepos
git pull $QUIET
find . -name '*.pyc' -delete
$PIP install $QUIET --editable .

# rattail-corepos
cd $SRC/rattail-corepos
git pull $QUIET
find . -name '*.pyc' -delete
$PIP install $QUIET --editable .

# tailbone-corepos
cd $SRC/tailbone-corepos
git pull $QUIET
find . -name '*.pyc' -delete
$PIP install $QUIET --editable .

## end corepos
% endif

## begin catapult
% if env.theo_integrates_with == 'catapult':

# onager
cd $SRC/onager
git pull $QUIET
find . -name '*.pyc' -delete
$PIP install $QUIET --editable .

# rattail-onager
cd $SRC/rattail-onager
git pull $QUIET
find . -name '*.pyc' -delete
$PIP install $QUIET --editable .

# tailbone-onager
cd $SRC/tailbone-onager
git pull $QUIET
find . -name '*.pyc' -delete
$PIP install $QUIET --editable .

## end catapult
% endif

## begin locsms
% if env.theo_integrates_with == 'locsms':

# luckysmores
cd $SRC/luckysmores
git pull $QUIET
find . -name '*.pyc' -delete
$PIP install $QUIET --editable .

# rattail-luckysmores
cd $SRC/rattail-luckysmores
git pull $QUIET
find . -name '*.pyc' -delete
$PIP install $QUIET --editable .

# tailbone-locsms
cd $SRC/tailbone-locsms
git pull $QUIET
find . -name '*.pyc' -delete
$PIP install $QUIET --editable .

## end locsms
% endif

# theo
cd $SRC/theo
git pull $QUIET
find . -name '*.pyc' -delete
$PIP install $QUIET --editable .

## end !production
% endif

# now upgrade *all* dependencies
% if env.theo_integrates_with == 'corepos':
$PIP install $QUIET --upgrade --upgrade-strategy eager tailbone-theo[app,corepos]
% elif env.theo_integrates_with == 'catapult':
$PIP install $QUIET --upgrade --upgrade-strategy eager tailbone-theo[app,catapult]
% elif env.theo_integrates_with == 'locsms':
$PIP install $QUIET --upgrade --upgrade-strategy eager tailbone-theo[app,locsms]
% else:
$PIP install $QUIET --upgrade --upgrade-strategy eager tailbone-theo[app]
% endif

# migrate database schema
cd ${envroot}
bin/alembic --config app/rattail.conf upgrade heads