#!/bin/sh

git status 2> /dev/null > /dev/null

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

if [ -z "$exabgp_version" ]; then
    if [ $? -eq  0 ]; then
        GIT_TAG=`git status | egrep 'detached at 3|4' | wc -l`
        if [ $GIT_TAG -eq 0 ]; then
            GIT_BRANCH=`git branch | grep "*" | awk '{ print $2}'`
            GIT_COMMIT=`git rev-parse --short=10 HEAD`
            export exabgp_version="5.0.8-$(date +%Y%m%d)+${GIT_BRANCH}-${GIT_COMMIT}"
        fi
    else
        export exabgp_version="5.0.8-$(date -r $0 +%Y%m%d)+uncontrolled"
    fi
fi

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

export EXABGP_ROOT=$path
export PYTHONPATH="$path"/src

# Prefer `python` binary when in a venv
INTS="$INTERPRETER python3 python pypy3"
if [ -d "${VIRTUAL_ENV}" ]; then
    INTS="$INTERPRETER python3 python 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', 'main.py')))][0]

print(os.path.join(path,'application','main.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" "$@"
