#!/usr/bin/env bash

set -e

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

if [[ -n "${1}" ]]; then
    target=".stack-work-${1}"
else
    target=".stack-work"
fi
shift

if [[ ! -d "${target}" ]]; then
    printf "%s does not exist or is no directory\n" "${target}" >&2
    exit 1
fi

if [[ "${target}" != ".stack-work" ]]; then
  if [[ -e .stack-work-clean ]]; then
      printf ".stack-work-clean exists\n" >&2
      exit 1
  fi

  move-back() {
      if [[ -d .stack-work ]]; then
          mv -v .stack-work "${target}"
      else
          mkdir -v "${target}"
      fi
      [[ -d .stack-work-clean ]] && mv -v .stack-work-clean .stack-work
  }

  mv -v .stack-work .stack-work-clean
  mv -v "${target}" .stack-work
  trap move-back EXIT
fi

(
    set -ex
    stack clean $@
)
