#!/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.
#

. shell-error

export LC_ALL=C LANG=C LANGUAGE=C

if [ -n "${MKI_RPMI_PRINT_FILES-}" ]; then
	#!/bin/sh -efu
	#
	# Copyright (C) 2009  Alexey Tourbin <at@altlinux.org>
	#
	# Pretend to be rpmi and print rpm filenames passed for installation
	#
	# SPDX-License-Identifier: GPL-2.0-or-later
	#

	TEMP=$(getopt -n "$PROG" -o iUevhr: -l fancypercent,root: \
		-l allfiles,badreloc,excludeconfigs,excludedocs,force,ignoresize,justdb \
		-l noconfigs,nocontexts,nodeps,nodocs,nofdigests,nomd5,noorder,noscripts,notriggers \
		-l oldpackage,percent,repackage,replacefiles,replacepkgs,test \
		-- "$@" ) || exit 1

	eval set -- "$TEMP"

	i='' U='' e=''

	while :; do
		case "$1" in
			-i) i=1 ;;
			-U) U=1 ;;
			-e) e=1 ;;
			-r|--root) shift ;;
			--) shift; break ;;
			*) ;;
		esac
		shift
	done

	if [ $# -lt 1 ]; then
		fatal "not enough arguments"
	elif [ -n "$e" ]; then
		fatal "cannot erase packages: $*"
	elif [ -z "$i$U" ]; then
		fatal "install command not recognized"
	fi

	print_rpmfile()
	{
		case "$1" in
			/*.rpm) printf '%s\n' "$1" ;;
			*) fatal "invalid argument${2:+ $2}: $1" ;;
		esac
	}

	for arg; do
		case "$arg" in
			/*/filelist.*)
				found=
				while read -r fname; do
					print_rpmfile "$fname" "from filelist"
					found=1
				done < "$arg"
				[ -n "$found" ] ||
					fatal "empty filelist"
				;;
			*)
				print_rpmfile "$arg"
				;;
		esac
	done >> "$MKI_RPMI_PRINT_FILES"
	exit
fi

. "${0%/*}"/mki-sh-functions

verbose "has started executing."

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

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

export MKI_RPMI_PRINT_FILES="$1"
shift

"$aptbox/apt-get" -q -y -o RPM::PM=external -o "Dir::Bin::rpm=$0" install -- "$@" >&2 || {
	rc=$?
	[ $rc -le 128 ] ||
		message "apt-get terminated by signal $(($rc-128))"
	fatal 'failed to calculate package file list.'
}

verbose 'calculated package file list.'
