#!/bin/sh

GIT_TAG=`git status | egrep 'detached at 3|4' | wc -l`
git status 2> /dev/null > /dev/null

# returns 128 if not in a git repo
# returns 127 if git is not installed

if [ $? -eq  0 ] && [ $GIT_TAG -eq 0 ]; then
   GIT_BRANCH=`git branch | grep "*" | awk '{ print $2}'`
   GIT_COMMIT=`git log -1 | head -1 | awk '{ print $2 }'`
   export EXABGP_VERSION="${GIT_BRANCH}-${GIT_COMMIT}"
fi


path="$(cd "$(dirname "$0")"/.. ; pwd)"

export PYTHONPATH="$path"/lib

# Prefer `python` binary when in a venv
INTS="$INTERPRETER python3 pypy3 python pyp"
if [ -d "${VIRTUAL_ENV}" ]; then
    INTS="$INTERPRETER python pypy python3 pypy3"
fi

for INTERPRETER in $(echo $INTS); do
    INTERPRETER="$(command -v "$INTERPRETER")" && break
done

if [ "$INTERPRETER" = "" ]; then
	echo "ExaBGP could not find a python interpreter"
	exit 1
fi

APPLICATION="$("$INTERPRETER" -c "
import sys
import os

path = [os.path.join(_,'exabgp')
        for _ in sys.path
        if os.path.isfile('/'.join((_, 'exabgp', 'application', 'bgp.py')))][0]

print(os.path.join(path,'application','bgp.py'))

def remove (file):
    try: os.remove(file)
    except: pass

if 'exabgp' not in os.environ.get('SKIPCLEANUP',''):
	[remove(os.path.join(r,f)) for r,d,fs in os.walk(path) for f in fs if f.endswith('.pyc')]

")"

exec "$INTERPRETER" "$APPLICATION" --root "$path" "$@"
