#!/usr/bin/env bash
# echo ${BASH_SOURCE[0]}
# HERE="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"

req="$1"

set -au

bdir=""

[[ -x ~/build/bin/mars.bin ]] && bdir=~/build/
[[ -x ~/build/mars-client/bin/mars.bin ]] && bdir=~/build/mars-client/
[[ -x ~/build/mars-client-bundle/bin/mars.bin ]] && bdir=~/build/mars-client-bundle/

[[ -z "$bdir" ]] && echo "couldn't find mars.bin executable" && exit 1

export MARS_LANGUAGE_FILE=~/git/mars-client-configs/etc/mars.def
export MARS_TEST_FILE=~/git/mars-client-configs/chk/mars.chk
export MARS_EMS_FILE=/tmp/mars.ems
export MARS_AUTH_FILE=/dev/null
export MARS_DISSEMINATION_SCHEDULE_FILE=/tmp/mars.schedule
export MARS_CONFIG=/tmp/mars.config
export FDB_HOME=/tmp/fdblocal/

mkdir -p $FDB_HOME/etc/fdb
cp $bdir/etc/fdb/schema $FDB_HOME/etc/fdb/

cat <<@ > $FDB_HOME/etc/fdb/config.yaml
---
type: dist
lanes:
- type: remote
  host: localhost
  port: 7655
- type: remote
  host: localhost
  port: 7656
@

cat <<@ > $MARS_CONFIG
database,
    class   = dhsbase,
    name    = localhost/dhslocal/local/marsod,
    retry   = 32767,
    timeout = 0,
    # rules   = '~/chk/marsod.chk',
    host    = 127.0.0.1,
    port    = 9000,
    obs     = 1

database,
    name    = file,
    class   = flatfilebase,
    visit   = false

database,
    class = fdb5base,
    name  = fdblocal/fdblocalhost/fdb,
    visit = false,
    timeout = 0,
    retry   = 32767,
    home = "$FDB_HOME",
    # rules = '~/chk/fdbmain.chk',
    host  = fdblocalhost # dummy

database,
    name=webmars,
    class=apibase,
    url='https://api.ecmwf.int/v1', 
    visit=false

database,
    name=webmars2,
    class=apibase,
    visit=false
@

cat<<@ > $MARS_EMS_FILE
$LOGNAME all
@

cat<<@ > $MARS_DISSEMINATION_SCHEDULE_FILE
allow, request=(empty)
@

echo "MARS client is $bdir/bin/mars.bin"

# export ECKIT_DEBUG=1
# export METKIT_DEBUG=1
# export FDB_DEBUG=1
# export MARS_DEBUG=1

MARS_DEBUGGER=${MARS_DEBUGGER:=}

if [[ $req != "" ]]
then
  export MARS_REQUEST="$req"
  $MARS_DEBUGGER $bdir/bin/mars.bin
else
  $MARS_DEBUGGER $bdir/bin/mars.bin || exit 1
fi
