#!/bin/ash -efu
#
# mki-pack-tar
#
# This file is part of mkimage
# Copyright (C) 2007-2009  Alexey Gladkov <gladkov.alexey@gmail.com>
#
# This file is covered by the GNU General Public License,
# which should be included with mkimage as the file COPYING.
#

. "${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%/*}")"

method=
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:-}" ;;
esac

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

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

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

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

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

if [ -n "${MKI_EXCLUDE:-}" ]; then
	for d in ${MKI_EXCLUDE:-}; do
		args="\$args --exclude \${d#/}"
	done
fi

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