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

if [ -z "${__included_mki_sh_functions:-}" ]; then
__included_mki_sh_functions=1

# shellcheck source=/bin/shell-error
. shell-error
# shellcheck source=/bin/shell-args
. shell-args

# shellcheck disable=SC2034
{
	verbose="${VERBOSE:+-v}"
	quiet="${QUIET:+-q}"

	workdirname=${WORKDIRNAME:?Work directory name required}
	outdirname=${OUTDIRNAME:?Out directory name required}
	#cachedirname=${CACHEDIRNAME:?Cache directory name required}

	bindir="${TOOLSDIR:?Helper directory required}"
	bindir="$(opt_check_dir 'TOOLSDIR' "$bindir")"

	curdir="${CURDIR:?Current directory required}"
	curdir="$(opt_check_dir 'CURDIR' "$curdir")"

	cachedir="${CACHEDIR:?cache required}"
	outdir="${OUTDIR:?Output directory required}"
	dir="${WORKDIR:?Work directory required}"
}

if [ -z "${include_without_workdir_check-}" ]; then
	cachedir="$(opt_check_dir 'CACHEDIR' "$cachedir")"
	outdir="$(opt_check_dir 'OUTDIR' "$outdir")"
	dir="$(opt_check_dir 'WORKDIR' "$dir")"
fi

# shellcheck disable=SC2034
{
	chroot="$dir/chroot"

	subdir="$chroot/$WORKDIRNAME"
	subchroot="$subdir/chroot"

	makefile="${MYMAKEFILE:?makefile required}"
	makefile="$(opt_check_read 'MYMAKEFILE' "$makefile")"
}

[ -s "$makefile" ] ||
	fatal "$makefile: Makefile is empty"

export PATH="$bindir:$PATH"

cp_args=
get_copy_args() {
	[ "$#" -ge 2 ] ||
		fatal "get_copy_args(): more arguments required"

	cp_args=
	[ "$(find "$@" -printf '%D\n' 2>/dev/null |sort -u |wc -l)" -eq 1 ] ||
		return 0
	# shellcheck disable=SC2034
	cp_args='-l'
}

make_exec() {
	cat > "$1"
	chmod 755 -- "$1"
}

run_chrooted() {
	local rc=0
	make_exec "$1/.host/run_chrooted.sh"
	mki-run "/.host/run_chrooted.sh" || rc=$?
	rm -f -- "$1/.host/run_chrooted.sh"
	return $rc
}

mki_list_pkgs() {
	local r
	for r in "$@"; do
		if [ -f "$r" ]; then
			grep -h '^[[:space:]]*[^#]' "$r" |
				tr ' ' '\n'
		else
			printf '%s\n' "$r"
		fi
	done |
		{
			if [ -z "$NO_SORT_PACKAGES" ]; then
				sort -u
			else
				cat
			fi
		}
}

print_environ_names() {
	printenv -0 |
		tr '\n\0' '_\n' |
		sed -rn -e 's#^([^=]+)=.*#\1#p'
}

fi
