#!/usr/bin/env bash

set -e

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

case $1 in
    "")
        exec -- stack clean
        ;;
    *)
        target=".stack-work-${1}"
        if [[ ! -d "${target}" ]]; then
            printf "%s does not exist or is no directory\n" "${target}" >&2
            exit 1
        fi
        if [[ -e .stack-work-clean ]]; then
            printf ".stack-work-clean exists\n" >&2
            exit 1
        fi

        move-back() {
            mv -v .stack-work "${target}"
            [[ -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

        stack clean
        ;;
esac
