#!/usr/bin/env bash

set -e

[ "${FLOCKER}" != "$0" ] && exec env FLOCKER="$0" flock -en .stack-work.lock "$0" "$@" || :

if ! in-develop | grep -q 'In develop'; then
    printf "Not in develop"
    exit 1
fi   

__HOST=${HOST:-$(hostname -s | awk '{ print $0; }')}

export DETAILED_LOGGING=${DETAILED_LOGGING:-true}
export LOG_ALL=${LOG_ALL:-false}
export LOGLEVEL=${LOGLEVEL:-info}
export DUMMY_LOGIN=${DUMMY_LOGIN:-true}
export SERVER_SESSION_ACID_FALLBACK=${SERVER_SESSION_ACID_FALLBACK:-true}
export SERVER_SESSION_COOKIES_SECURE=${SERVER_SESSION_COOKIES_SECURE:-false}
export COOKIES_SECURE=${COOKIES_SECURE:-false}
export ALLOW_DEPRECATED=${ALLOW_DEPRECATED:-true}
export ENCRYPT_ERRORS=${ENCRYPT_ERRORS:-false}
export RIBBON=${RIBBON:-${__HOST:-localhost}}
export APPROOT=${APPROOT:-http://localhost:$((${PORT_OFFSET:-0} + 3000))}
unset HOST

move-back() {
    mv -vT .stack-work .stack-work-run
    [[ -d .stack-work-build ]] && mv -vT .stack-work-build .stack-work
}

if [[ -d .stack-work-run ]]; then
    [[ -d .stack-work ]] && mv -vT .stack-work .stack-work-build
    mv -vT .stack-work-run .stack-work
    trap move-back EXIT
fi

if ! [ -z "$(which yesod)" ]
then
  yesod devel -p $((${PORT_OFFSET:-0} + 3000)) -q $((${PORT_OFFSET:-0} + 3443)) $@
elif ! [ -z "$(which stack)" ]
then
  stack exec -- yesod devel -p $((${PORT_OFFSET:-0} + 3000)) -q $((${PORT_OFFSET:-0} + 3443)) $@
else
  exit 1
fi
