#!/bin/bash -e

DEBUG=${DEBUG:-n}

info() { echo "INFO: $*"; }
warn() { echo "WARN: $*" >&2; }
fatal() { echo "FATAL: $*" >&2; exit 1; }

usage() {
    exit_code=$1
    shift
    [[ $# -eq 0 ]] || echo "FATAL: $*"
    cat <<EOF
$(basename "$0") TARGET

    Rewind build to TARGET layer.

    Select the latest target you want to still exist.

    Valid targets:
        root.patched
        root.build
        bootstrap

    Env vars::

        DEBUG       - set to 'y' for verbose output (set -x)
        RELEASE     - distro and codename in use. E.g. debian/bullseye
                      If unset, will fallback to CODENAME
        CODENAME    - distro codename in use. If unset, will fall back to
                      system codename (i.e. '$(lsb_release -sc)')

EOF
    exit "$exit_code"
}

[[ "$DEBUG" != 'y' ]] || set -x

codename="$(lsb_release -sc)"
if [[ -n "$RELEASE" ]]; then
    codename=$(basename "$RELEASE")
elif [[ -n "$CODENAME" ]]; then
    codename=$CODENAME
else
    warn "RELEASE and CODENAME unset, using $codename"
fi

targets=("bootstrap" "root.build" "root.patched")
target=$1

if [[ "$target" == "help" ]]; then
    usage
elif [[ " ${targets[*]} " != *" ${target} "* ]]; then
    usage 1 "Only valid targets can be used."
fi

stop_services() {
    local targ=$1
    if [[ -d "$targ" ]]; then
        info "Stopping processes in $targ"
        fuser -k "$targ"
    fi
}

undeck() {
    local targ=$1
    if [[ -d build/$targ ]]; then
        stop_services "$targ"
        if [[ "$targ" == "cdroot" ]]; then
            rm -rf build/product.iso
        else
            deck -D "build/$targ"
        fi
    fi
    rm -rf "build/$targ"
    rm -f "build/stamps/$targ"
}

mount_if_not_mounted() {
    local target=${1}
    if deck --ismounted "$target"; then
        return
    else
        deck "build/${target}"
     fi
}

# cdroot is not a deck - but 'undeck' handles it anyway
undeck cdroot
undeck root.sandbox

case $target in
    # nothing more needed for root.patched
    root.build)
        undeck root.patched
        ;;
    bootstrap)
        undeck root.patched
        undeck root.build
        ;;
esac
mount_if_not_mounted "$target"
