#!/bin/ash -efu
#
# mki-copy-pkgs
#
# 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."

destdir="${MKI_DESTDIR:-}"
aptboxdir="${PKGBOX:?global aptbox required}"

tempdir="$dir/$PROG.verbose"
exit_handler() {
    local rc=$?
    trap - EXIT
    [ ! -d "$tempdir" ] || rm -rf -- "$tempdir"
    exit $rc
}

if [ -n "$verbose" ]; then
	[ ! -d "$tempdir" ] || rm -rf -- "$tempdir"
else
	trap exit_handler HUP INT QUIT TERM EXIT
fi
mkdir $verbose -- "$tempdir"

lstfile="$tempdir/lst"
errfile="$tempdir/err"
reqfile="$tempdir/req"

# don't put all the lists into one apt call but allow copying
# conflicting packages coming from different package lists
for i in "$@"; do
	mki_list_pkgs "$i"
done > "$reqfile"

if [ ! -s "$reqfile" ]; then
	message "Nothing to do."
	exit 0
fi

> "$lstfile"
> "$errfile"

buildlist() {
	local rc=0

	xargs -r mki-print-uris 2>"$errfile" >> "$lstfile" < "$1" ||
		rc=$?

	if [ "$rc" -eq 0 ]; then
		echo >> "$lstfile"
		return 0
	fi

	local conflicts
	if ! conflicts="$(LANG=C fgrep ': Conflicts: ' "$errfile")"; then
		cat -- "$errfile" >&2
		fatal 'could not copy packages.'
	fi

	printf '%s\n' "$conflicts" > "$errfile"
	return 1
}

processfile() {
	local file size

	file="$1"; shift
	size="$1"; shift

	! buildlist "$file" ||
		return 0

	if [ "$size" -eq 1 ]; then
		verbose 'Conflicts packages found in requires list: '
		[ -z "$verbose" ] ||
			cat -- "$errfile" >&2

		message 'could not copy packages: conflicts found.'
		return 1
	fi

	local n_head n_tail

	n_head="$(($size/2))"
	n_tail="$n_head"

	if [ "$size" != "$(($n_head*2))" ]; then
		n_tail="$n_head"
		n_head="$(($n_head+1))"
	fi

	local temp
	temp="$(mktemp "$tempdir/temp.XXXXXXXXX")" ||
		fatal "unable to make temporary file."

	head -n $n_head "$file" > "$temp"
	if ! processfile "$temp" "$n_head"; then
		rm -f -- "$temp"
		return 1
	fi

	tail -n $n_tail "$file" > "$temp"
	if ! processfile "$temp" "$n_tail"; then
		rm -f -- "$temp"
		return 1
	fi

	rm -f -- "$temp"
}

processfile "$reqfile" "$(wc -l < "$reqfile")" ||
	exit "$?"

[ -s "$lstfile" ] ||
	fatal 'could not copy packages: empty list.'

sort -u "$lstfile" |
	tr ' ' '\n' |
	xargs -r cp $verbose -ut "$chroot/.in/" -- ||
	fatal 'could not copy packages: copy failed.'

make_exec "$chroot/.host/script.sh" <<EOF
#!/bin/sh -efu
mkdir $verbose -p -- '/.image/$destdir'
/.host/find /.in -mindepth 1 -maxdepth 1 -execdir cp $verbose -alft '/.image/$destdir' -- '{}' '+'
EOF

rc=0
mki-run "/.host/script.sh" || rc=$?
rm -f -- "$chroot/.host/script.sh"
find "$chroot/.in/" -mindepth 1 -maxdepth 1 -execdir rm $verbose -rf -- '{}' '+'
exit $rc
