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

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

verbose "has started executing."

pkgs="${PACKAGES_REQUIRED_PACK_TAR:-}"

outname="${MKI_OUTNAME:-outname}"
outname="${outname##*/}"

imgsubdir="${MKI_IMAGESUBDIR:-}"
imgsubdir="${imgsubdir#/}"

[ "$MKI_OUTNAME" = "${MKI_OUTNAME##*/}" ] ||
	outdir="$(readlink -ev "${MKI_OUTNAME%/*}")"

case "${MKI_TAR_COMPRESS:-}" in
	xz)                  method='--xz';    pkgs="$pkgs ${PACKAGES_REQUIRED_PACK_XZ:-}" ;;
	lzma)                method='--lzma';  pkgs="$pkgs ${PACKAGES_REQUIRED_PACK_LZMA:-}" ;;
	bzip2|bz2|tarbz2|-j) method='--bzip2'; pkgs="$pkgs ${PACKAGES_REQUIRED_PACK_BZIP2:-}" ;;
	gzip|gz|targz|-z)    method='--gzip';  pkgs="$pkgs ${PACKAGES_REQUIRED_PACK_GZIP:-}" ;;
	zst|zstd)            method='--zstd';  pkgs="$pkgs ${PACKAGES_REQUIRED_PACK_ZSTD:-}" ;;
	lz4)                 method='--lz4';   pkgs="$pkgs ${PACKAGES_REQUIRED_PACK_LZ4:-}" ;;
	*)                   method='' ;;
esac

[ -d "$chroot" ] ||
	fatal "$dir: not look like a work directory of hasher."

mki-install $pkgs ||
	fatal "failed to install packages: $pkgs."

run_chrooted "$chroot" > "$outdir/$outname" <<EOF
#!/bin/sh -efu
cd /.image/

[ -z "$imgsubdir" ] || [ ! -d "./$imgsubdir" ] || cd "./$imgsubdir"

args=
[ ! -d .in ]       || args="\$args --exclude .in"
[ ! -d .host ]     || args="\$args --exclude .host"
[ ! -f .fakedata ] || args="\$args --exclude .fakedata"

for dir in ${MKI_EXCLUDE:-}; do
	args="\$args --exclude \${dir#/}"
done

exec tar --numeric-owner \$args $method -cf - .
EOF
