#!/bin/bash

shopt -s nocasematch

cd $(dirname $0)

AGENT="$1"
shift
ARGS=""

TRACE_ENABLED=""
TRACE_TAG=acapy.events
if ! [ -z "$TRACE_TARGET_URL" ]; then
  TRACE_TARGET=http://${TRACE_TARGET_URL}/
else
  TRACE_TARGET=log
fi
if [ -z "$DOCKER_NET" ]; then
  DOCKER_NET="bridge"
fi

for i in "$@"
do
  if [ ! -z "$SKIP" ]; then
    SKIP=""
    continue
  fi
  case $i in
  --events)
    if [ "${AGENT}" = "performance" ]; then
      echo -e "\nIgnoring the \"--events\" option when running the ${AGENT} agent.\n"
    else
      EVENTS=1
    fi
    continue
  ;;
    --self-attested)
      SELF_ATTESTED=1
      continue
    ;;
    --trace-log)
      TRACE_ENABLED=1
      TRACE_TARGET=log
      TRACE_TAG=acapy.events
      continue
    ;;
    --trace-http)
      TRACE_ENABLED=1
      TRACE_TARGET=http://${TRACE_TARGET_URL}/
      TRACE_TAG=acapy.events
      continue
    ;;
    --debug-ptvsd)
      ENABLE_PTVSD=1
      continue
    ;;
    --debug-pycharm)
      ENABLE_PYDEVD_PYCHARM=1
      continue
    ;;
    --debug-pycharm-controller-port)
      PYDEVD_PYCHARM_CONTROLLER_PORT=$2
      SKIP=1
      continue
    ;;
    --debug-pycharm-agent-port)
      PYDEVD_PYCHARM_AGENT_PORT=$2
      SKIP=1
      continue
    ;;
  --timing)
    if [ ! -d "../logs" ]; then
      mkdir ../logs && chmod -R uga+rws ../logs
    fi
    if [ "$(ls -ld ../logs | grep dr..r..rwx)" == "" ]; then
      echo "Error: To use the --timing parameter, the directory '../logs' must exist and all users must be able to write to it."
      echo "For example, to create the directory and then set the permissions use: 'mkdir ../logs; chmod uga+rws ../logs'"
      exit 1
    fi
    continue
  ;;
  --bg)
    if [ "${AGENT}" = "alice" ] || [ "${AGENT}" = "faber" ] || [ "${AGENT}" = "acme" ]; then
      DOCKER_OPTS="-d"
      echo -e "\nRunning in ${AGENT} in the background. Note that you cannot use the command line console in this mode."
      echo To see the logs use: \"docker logs ${AGENT}\".
      echo While viewing logs, hit CTRL-C to return to the command line.
      echo To stop the agent, use: \"docker stop ${AGENT}\". The docker environment will
      echo -e "be removed on stop.\n\n"
    else
      echo The "bg" option \(for running docker in detached mode\) is only for agents Alice, Faber and Acme.
      echo Ignoring...
    fi
    continue
  ;;
  --help)
    cat <<EOF

Usage:
   ./demo_run <agent> [OPTIONS]

   - <agent> is one of alice, faber, acme, performance, vsw, vsw-user, repo.
   - Options:
      --events - display on the terminal the webhook events from the ACA-Py agent.
      --timing - at the end of the run, display timing; relevant to the "performance" agent.
      --bg - run the agent in the background; for use when using OpenAPI/Swagger interface
          --trace-log - log events to the standard log file
          --trace-http - log events to an http endmoint specified in env var TRACE_TARGET_URL
          --self-attested - include a self-attested attribute in the proof request/response
      debug options: --debug-pycharm-agent-port <port>; --debug-pycharm-controller-port <port>
                    --debug-pycharm; --debug-ptvsd

EOF
    exit 0
  ;;
  esac
  ARGS="${ARGS:+$ARGS }$i"
done

if [ "$AGENT" = "faber" ]; then
  AGENT_MODULE="faber"
  AGENT_PORT=8020
  AGENT_PORT_RANGE=8020-8027
elif [ "$AGENT" = "alice" ]; then
  AGENT_MODULE="alice"
  AGENT_PORT=8030
  AGENT_PORT_RANGE=8030-8037
elif [ "$AGENT" = "acme" ]; then
  AGENT_MODULE="acme"
  AGENT_PORT=8040
  AGENT_PORT_RANGE=8040-8047
elif [ "$AGENT" = "performance" ]; then
  AGENT_MODULE="performance"
  AGENT_PORT=8030
  AGENT_PORT_RANGE=8030-8038
elif [ "$AGENT" = "vsw" ]; then
  AGENT_MODULE="vsw"
  AGENT_PORT=8050
  AGENT_PORT_RANGE=8050-8057
elif [ "$AGENT" = "vsw_user" ]; then
  AGENT_MODULE="vsw_user"
  AGENT_PORT=8070
  AGENT_PORT_RANGE=8070-8077
elif [ "$AGENT" = "repo" ]; then
  AGENT_MODULE="repo"
  AGENT_PORT=8060
  AGENT_PORT_RANGE=8060-8067
else
  echo "Please specify which agent you want to run. Choose from 'faber', 'alice', 'acme', 'performance', 'vsw', 'vsw_user', or 'repo'."
  exit 1
fi

echo "Preparing agent image..."
docker build -q -t faber-alice-demo -f ../docker/Dockerfile.demo .. || exit 1

if [ ! -z "$DOCKERHOST" ]; then
  # provided via APPLICATION_URL environment variable
  export RUNMODE="docker"
elif [ -z "${PWD_HOST_FQDN}" ]; then
  DOCKERHOST=`docker run --rm --net=host eclipse/che-ip`
  export RUNMODE="docker"
else
  PWD_HOST="${PWD_HOST_FQDN}"
  if [ "$PWD_HOST_FQDN" = "labs.play-with-docker.com" ]; then
    export ETH_CONFIG="eth1"
  elif [ "$PWD_HOST_FQDN" = "play-with-docker.vonx.io" ]; then
    export ETH_CONFIG="eth0"
  else
    export ETH_CONFIG="eth0"
  fi
  MY_HOST=`ifconfig ${ETH_CONFIG} | grep inet | cut -d':' -f2 | cut -d' ' -f1 | sed 's/\./\-/g'`
  export DOCKERHOST="ip${MY_HOST}-${SESSION_ID}-{PORT}.direct.${PWD_HOST_FQDN}"
  export RUNMODE="pwd"
fi

# check if ngrok is running on our $AGENT_PORT (don't override if AGENT_ENDPOINT is already set)
if [ -z "$AGENT_ENDPOINT" ] && [ "$RUNMODE" == "docker" ]; then
  echo "Trying to detect ngrok service endpoint"
  JQ=${JQ:-`which jq`}
  if [ -x "$JQ" ]; then
    NGROK_ENDPOINT=$(curl --silent localhost:4040/api/tunnels | $JQ -r '.tunnels[0].public_url')
    if [ -z "$NGROK_ENDPOINT" ] || [ "$NGROK_ENDPOINT" = "null" ]; then
      echo "ngrok not detected for agent endpoint"
    else
      export AGENT_ENDPOINT=$NGROK_ENDPOINT
      echo "Detected ngrok agent endpoint [$AGENT_ENDPOINT]"
    fi
  else
    echo "jq not found"
  fi
fi

echo $DOCKERHOST

DOCKER_ENV="-e LOG_LEVEL=${LOG_LEVEL} -e RUNMODE=${RUNMODE} -e DOCKERHOST=${DOCKERHOST}"
if ! [ -z "$AGENT_PORT" ]; then
  DOCKER_ENV="${DOCKER_ENV} -e AGENT_PORT=${AGENT_PORT}"
fi
if ! [ -z "$POSTGRES" ]; then
  DOCKER_ENV="${DOCKER_ENV} -e POSTGRES=1 -e RUST_BACKTRACE=1"
fi
if ! [ -z "$LEDGER_URL" ]; then
  GENESIS_URL="${LEDGER_URL}/genesis"
  DOCKER_ENV="${DOCKER_ENV} -e LEDGER_URL=${LEDGER_URL}"
fi
if ! [ -z "$GENESIS_URL" ]; then
  DOCKER_ENV="${DOCKER_ENV} -e GENESIS_URL=${GENESIS_URL}"
fi
if ! [ -z "$AGENT_ENDPOINT" ]; then
  DOCKER_ENV="${DOCKER_ENV} -e AGENT_ENDPOINT=${AGENT_ENDPOINT}"
fi
if ! [ -z "$EVENTS" ]; then
  DOCKER_ENV="${DOCKER_ENV} -e EVENTS=1"
fi
if ! [ -z "$SELF_ATTESTED" ]; then
  DOCKER_ENV="${DOCKER_ENV} -e SELF_ATTESTED=${SELF_ATTESTED}"
fi
if ! [ -z "$TRACE_TARGET" ]; then
  DOCKER_ENV="${DOCKER_ENV} -e TRACE_TARGET=${TRACE_TARGET}"
  DOCKER_ENV="${DOCKER_ENV} -e TRACE_TAG=${TRACE_TAG}"
  DOCKER_ENV="${DOCKER_ENV} -e TRACE_ENABLED=${TRACE_ENABLED}"
fi
# if $TAILS_NETWORK is specified it will override any previously specified $DOCKER_NET
if ! [ -z "$TAILS_NETWORK" ]; then
  DOCKER_NET="${TAILS_NETWORK}"
  DOCKER_ENV="${DOCKER_ENV} -e TAILS_NETWORK=${TAILS_NETWORK}"
  DOCKER_ENV="${DOCKER_ENV} -e TAILS_NGROK_NAME=ngrok-tails-server"
fi
if ! [ -z "$PUBLIC_TAILS_URL" ]; then
  DOCKER_ENV="${DOCKER_ENV} -e PUBLIC_TAILS_URL=${PUBLIC_TAILS_URL}"
fi
if ! [ -z "$TAILS_FILE_COUNT" ]; then
  DOCKER_ENV="${DOCKER_ENV} -e TAILS_FILE_COUNT=${TAILS_FILE_COUNT}"
fi

if ! [ -z "${ENABLE_PYDEVD_PYCHARM}" ]; then
  DOCKER_ENV="${DOCKER_ENV} -e ENABLE_PYDEVD_PYCHARM=${ENABLE_PYDEVD_PYCHARM} -e PYDEVD_PYCHARM_CONTROLLER_PORT=${PYDEVD_PYCHARM_CONTROLLER_PORT} -e PYDEVD_PYCHARM_AGENT_PORT=${PYDEVD_PYCHARM_AGENT_PORT}"
fi

# on Windows, docker run needs to be prefixed by winpty
if [ "$OSTYPE" = "msys" ]; then
  DOCKER="winpty docker"
fi
DOCKER=${DOCKER:-docker}

$DOCKER run --name $AGENT --rm -it ${DOCKER_OPTS} \
  --network=${DOCKER_NET} \
  -p 0.0.0.0:$AGENT_PORT_RANGE:$AGENT_PORT_RANGE \
  -v "/$(pwd)/../logs:/home/indy/logs" \
  -v "$HOME/vsw:/home/indy/vsw" \
  $DOCKER_ENV \
  faber-alice-demo $AGENT_MODULE --port $AGENT_PORT $ARGS
