#!/bin/sh -efu
# SPDX-License-Identifier: GPL-3.0-or-later
# Copyright (C) 2007-2023  Alexey Gladkov <gladkov.alexey@gmail.com>

# retval = 0 - cached
# retval = 1 - not cached

# shellcheck source=tools/mki-sh-functions
. "${0%/*}"/mki-sh-functions

verbose "has started executing."

[ "$#" -eq 2 ] ||
	fatal "Usage: $PROG <check | build> <target>"

action="$1"; shift

if [ -n "${NO_CACHE:-}" ] && [ "$action" = 'check' ]; then
	verbose "Cache disabled"
	exit 1
fi

cache_type="$1"

[ -f "${0%/*}/mki-cache-$cache_type" ] ||
	fatal "$cache_type: unknown target"

cachefile="$cachedir/mki/$cache_type"

workdir_check_status() {
	return 0
}

workdir_changed="$cachedir/status/workdir-changed"
workdir_change_status() {
	mkdir -p -- "$workdir_changed"
}

payload_makefile() {
	sha256sum "$makefile" |
		cut -d\  -f1
}

payload_file_state() {
	local is_dir=
	[ ! -d "$1" ] || is_dir=1
	[ -z "$is_dir" ] || cd "$1"

	stat --printf='%A\t%s\t%Y\t%n\n' "$2"

	[ -z "$is_dir" ] || cd - >/dev/null
}

payload_directory_state() {
	[ -d "$1" ] ||
		return 0

	cd "$1" ||
		return

	local rc=0
	find . -mindepth 1 -printf '%M\t%s\t%T@\t%p\n' |
		LANG=C sort

	cd - >/dev/null
	return "$rc"
}


payload_apt_list_release() {
	[ -d "$1" ] ||
		return 0
	find "$1" \
		\( \
			   -name '*_release' \
			-o -name '*_InRelease' \
		\) \
		-execdir sed -rn \
			-e '/^MD5Sum:/,            /^[^[:space:]]/ { s/^[[:space:]]//p; }' \
			-e '/^BLAKE[[:alnum:]]+:/, /^[^[:space:]]/ { s/^[[:space:]]//p; }' \
			-e '/^SHA[[:alnum:]]+:/,   /^[^[:space:]]/ { s/^[[:space:]]//p; }' \
			'{}' '+' |
		LANG=C sort
}

payload_image_packages()
{
	local r
	for r in ${IMAGE_PACKAGES:-} ${IMAGE_PACKAGES_REGEXP:-}; do
		if [ -f "$r" ]; then
			r="$(readlink -ev "$r")" ||
				continue
			payload_file_state / "$r"
		else
			printf '%s\n' "$r"
		fi
	done |
		LANG=C sort
}

. "mki-cache-$cache_type"

errlock="$cachedir/mki/$cache_type.error"
sha="`{ payload || mkdir -- "$errlock"; } |sha256sum - |cut -d\  -f1`"

if [ -d "$errlock" ]; then
	rm -rf -- "$errlock"
	fatal "Unable to collect payload."
fi

invalid_cache() {
	printf '%s\n' "$sha" > "$cachefile"
	[ "$action" = 'build' ] ||
		workdir_change_status
	exit ${1:-1}
}

[ "$action" != 'build' ] ||
	invalid_cache 0

[ -s "$cachefile" ] ||
	invalid_cache

old_sha="`head -1 "$cachefile"`"
[ "$old_sha" = "$sha" ] ||
	invalid_cache

workdir_check_status ||
	invalid_cache
