#!/usr/bin/env bash

set -e

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

__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}}
unset HOST

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

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

if ! [ -z "$(which yesod)" ]
then
  yesod devel $@
elif ! [ -z "$(which stack)" ]
then
  stack exec -- yesod devel $@
else
  exit 1
fi
