#!/bin/bash

function usage() {
    echo "usage: layer_hash LAYER_LABEL [IGNORE_SELF]"
    echo "    => compute a hash for (installed) layer (with dependencies)"
    echo "    => if IGNORE_SELF is set, we compute only a hash with dependencies"
}
function echoerr() {
    echo "$@" 1>&2;
}

if test "${1}" = ""; then
    usage
    exit 1
fi
if test "${1}" = "--help"; then
    usage
    exit 0
fi
IGNORE_SELF=0
if test "${2}" = "IGNORE_SELF"; then
    IGNORE_SELF=1
fi

LAYER_LABEL="${1}"

LAYER_HOME=$(get_layer_home "${LAYER_LABEL}" 2>/dev/null)
if test "${LAYER_HOME}" = ""; then
    if test "${LAYER_LABEL}" = "root@mfext"; then
        # maybe get_layer_home is not installed at this time
        LAYER_HOME=${MFEXT_HOME}
    else
        echo "ERROR: can't find layer home for label: ${LAYER_LABEL}"
        exit 1
    fi
fi

export LC_ALL=C
TMPHASH=/tmp/layer_hash.$$
rm -f "${TMPHASH}"
touch "${TMPHASH}"
if test "${LAYER_LABEL}" = "root@mfext"; then
    # special case because layer_wrapper can be not installed at this time
    DEPS="root@mfext#${LAYER_HOME}"
else
    DEPS=$(layer_wrapper --empty --layers="${LAYER_LABEL}" -- layers --raw --loaded-filter=yes |sed "s/ /#/g" |sort)
fi
for DEP in ${DEPS}; do
    LAB=$(echo "${DEP}" |awk -F '#' '{print $1;}')
    HOM=$(echo "${DEP}" |awk -F '#' '{print $2;}')
    if test "${LAB}" = "${LAYER_LABEL}"; then
        TYP="self"
        if test "${IGNORE_SELF}" = "1"; then
            continue
        fi
    else
        TYP="dependency"
    fi
    if test -f "${HOM}/.dhash"; then
        HTMP=$(cat "${HOM}/.dhash" |md5sum |awk '{print $1;}')
        echoerr "${LAB} layer (${TYP}) hash (from cache): ${HTMP}"
    else
        HTMP=$(_layer_hash "${LAB}")
        echoerr "${LAB} layer (${TYP}) hash: ${HTMP}"
    fi
    echo "${HTMP}" >>"${TMPHASH}"
done
cat "${TMPHASH}" |md5sum |awk '{print $1;}'
rm -f "${TMPHASH}"
