#!/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

[[ " ${targets[*]} " =~ " ${target} " ]] || usage 1 "Only valid targets can be used."

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
            rm -rf build/$targ
        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
        targets_array_len=${#targets[@]}
        for (( i=0; i<${targets_array_len}; i++ )); do
            if [[ "${targets[$i]}" == "bootstrap" ]]; then
                deck $FAB_PATH/bootstraps/$codename build/bootstrap
            else
                deck build/${target}
            fi
        done
     fi
}

case $target in
    root.patched)
        undeck cdroot
        undeck root.sandbox
        mount_if_not_mounted $target
        ;;
    root.build)
        undeck cdroot
        undeck root.sandbox
        undeck root.patched
        mount_if_not_mounted $target
        ;;
    bootstrap)
        undeck cdroot;
        undeck root.sandbox
        undeck root.patched
        undeck root.build
        mount_if_not_mounted $target
        ;;
    help)
        usage 0
        ;;
    *)
        usage 1 "Unknown target: '$target'"
esac
