#!/bin/bash

PORT=8000
ADDRESS="127.0.0.1"
SETTINGS="drams.local-settings"
ORIGINAL_PWD=`pwd`

while getopts ":a:p:s:h:address:port:settings:help" opt; do
  case ${opt} in
    a|address) ADDRESS="${OPTARG}"
    ;;
    p|port) PORT="${OPTARG}"
    ;;
    s|settings) SETTINGS="$OPTARG"
    ;;
    h|help)
        echo "start_fair_registry [-p <port>][-a <address>]"
        exit 0
    ;;
    \?) echo "Invalid option -${OPTARG} see -h" >&2
    ;;
  esac
done

FULL_ADDRESS="${ADDRESS}:${PORT}"

if ! [[ "$PORT" =~ ^[0-9]+$ ]]; then
    echo "Invalid port '$PORT' specified"
    exit 1
fi

echo Using Django Settings Module: ${SETTINGS}
export DJANGO_SETTINGS_MODULE="${SETTINGS}"
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
FAIR_HOME="$(dirname "${DIR}")"
cd $FAIR_HOME

echo "Attempting to start Registry on ${FULL_ADDRESS}"
nohup "$FAIR_HOME"/venv/bin/python "$FAIR_HOME"/manage.py runserver ${FULL_ADDRESS} > $FAIR_HOME/output.log 2>&1 &
echo $PORT > $FAIR_HOME/session_port.log
echo $ADDRESS > $FAIR_HOME/session_address.log

if [[ "$ADDRESS" == "0.0.0.0" ]]; then
    echo "Bound to All Addresses (0.0.0.0) setting to loopback address 127.0.0.1"
    ADDRESS="127.0.0.1"
fi

FULL_ADDRESS="${ADDRESS}:${PORT}"

count=0
until [ $count -gt 6 ] || curl http://${FULL_ADDRESS} > /dev/null 2>&1
do
    sleep 1
    ((count++))
done

curl http://${FULL_ADDRESS} > /dev/null 2>&1
retVal=$?
retVal=$(($retVal + 0))
if [ $retVal -ne 0 ]; then
    echo Error starting local registry at ${FULL_ADDRESS} error: $retVal
else
    echo Local registry now accepting connections on http://${FULL_ADDRESS}
fi

"$FAIR_HOME"/venv/bin/python "$FAIR_HOME"/manage.py get_token > "$FAIR_HOME"/token
chmod 600 "$FAIR_HOME"/token
echo An access token for the REST API is available in the file "$FAIR_HOME"/token

type -P "dot" &> /dev/null
retVal=$?
if [ $retVal -ne 0 ]; then
    echo WARNING: Graphviz is not installed, so provenance report images are not available
fi

unset DJANGO_SETTINGS_MODULE
cd $ORIGINAL_PWD
