#!/bin/sh

if [ "$1" = "-h" -o "$1" = "--help" ] ; then
    echo "Usage: [PY=optional/path/python] $0"
    echo
    echo "Run Anchor with default uwsgi settings. It will spawn 4 workers"
    echo "and use either the default reachable 'python' or one defined in the"
    echo "\$PY variable."
    echo
    exit 0
fi

if ! which uwsgi > /dev/null ; then
    echo "You need to install uwsgi to run anchor using this script."
    exit 1
fi

PY=${PY:-python}

if ! [ -x "$PY" ] ; then
    if ! [ -x "$(which "$PY")" ] ; then
        echo "Python interpreter not found (use PY variable to specify)."
        exit 1
    fi
fi

STR="import pkg_resources; print(pkg_resources.get_distribution('anchor').location)"
PKG_PATH=$("$PY" -c "$STR")

if ! [ -d "$PKG_PATH" ] ; then
    echo "Cannot find installed anchor package."
    exit 1
fi

if [ -z "$VIRTUAL_ENV" ]; then
    OPTS="-p 4"
else
    OPTS="--venv ""${VIRTUAL_ENV}"" -p 4"
fi

uwsgi --http-socket :5016 \
    --pecan "${PKG_PATH}/anchor/config.py" \
    ${OPTS}
