#!/bin/ash -efu
#
# mki-print-uris
#
# This file is part of mkimage
# Copyright (C) 2007-2012  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."

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

export LC_ALL=C LANG=C LANGUAGE=C

# assumed: defined aptbox
APT_Get_PrintLocalFile=
out=

aptbox="$aptboxdir/aptbox"
[ -d "$aptbox" ] ||
	fatal "$aptbox: Not a directory"

if ! out="$("$aptbox/apt-get" -q -y --print-uris install -- "$@" 2>&1)"; then
	printf %s\\n "$out" >&2
	fatal 'failed to calculate package file list.'
fi

all_pattern="'\\([a-z]\\+\\):\\([^']\\+\\)' .*"
local_pattern="'\\(file\\|copy\\):\\([^']\\+\\)' .*"

if ! all_uris="$(printf %s "$out" |sed -ne "s/^$all_pattern/\\2/pg")"; then
	printf %s\\n "$out" >&2
	fatal 'failed to filter package file list.'
fi

cached_uris=
if ! local_uris="$(printf %s "$out" |sed -ne "s/^$local_pattern/\\2/pg")"; then
	printf %s\\n "$out" >&2
	fatal 'failed to filter package file list.'
fi

if [ "$all_uris" != "$local_uris" ]; then
	if [ -z "$APT_Get_PrintLocalFile" ]; then
		if ! out="$("$aptbox/apt-get" -o APT::Get::PrintLocalFile=yes -q -y --print-uris install -- "$@" 2>&1)"; then
			printf %s\\n "$out" >&2
			fatal 'calculated package file list is not local and apt-get does not support APT::Get::PrintLocalFile option.'
		fi

		if ! cached_uris="$(printf %s "$out" |sed -ne "s/^$all_pattern/\\2/pg")" ||
		   [ -n "$cached_uris" ]; then
			printf %s\\n "$out" >&2
			fatal 'calculated package file list is not local and apt-get does not support APT::Get::PrintLocalFile option.'
		fi

		APT_Get_PrintLocalFile=1
	fi

	if [ -n "$verbose" ]; then
		"$aptbox/apt-get" -y -d install -- "$@" >&2 ||
			fatal 'failed to download packages from calculated package file list.'
	else
		if ! out="$("$aptbox/apt-get" -y -d install -- "$@" 2>&1)"; then
			printf %s\\n "$out" >&2
			fatal 'failed to download packages from calculated package file list.'
		fi
	fi

	if ! out="$("$aptbox/apt-get" -o APT::Get::PrintLocalFile=yes -q -y --print-uris install -- "$@" 2>&1)"; then
		printf %s\\n "$out" >&2
		fatal 'failed to calculate local package file list.'
	fi

	if ! cached_uris="$(printf %s "$out" |grep ^/)" || [ -z "$cached_uris" ]; then
		printf %s\\n "$out" >&2
		fatal 'failed to calculate local package file list.'
	fi
fi

if [ -n "$cached_uris" ]; then
	[ -n "$local_uris" ] && local_uris="$local_uris
$cached_uris" || local_uris="$cached_uris"
fi

printf %s\\n "$local_uris" |
	sed -e '/^[[:space:]]*$/d'
verbose 'calculated package file list.'
