#!/bin/sh
#
# binfmts trigger.
#
# Binaries can be specified like:
#  binfmts="<path> [<args> ...]"
#
# Arguments:	$ACTION = [run/targets]
#		$TARGET = [post-install/pre-remove]
#		$PKGNAME
#		$VERSION
#		$UPDATE = [yes/no]
#
ACTION="$1"
TARGET="$2"
PKGNAME="$3"
VERSION="$4"
UPDATE="$5"

export PATH="usr/bin:usr/sbin:/usr/sbin:/usr/bin:/sbin:/bin"

# {install,remove}_binfmts: legacy installation style
install_binfmts() {
	echo "$binfmts" | while read -r line; do
		set -- $line
		_bin="$1"; shift
		_bname="${_bin##*/}"
		update-binfmts --package "${PKGNAME}" --install "${_bname}" "${_bin}" "$@"
	done
}

remove_binfmts() {
	echo "$binfmts" | while read -r line; do
		set -- $line
		_bin="$1"; shift
		_bname="${_bin##*/}"
		if [ -f "var/lib/binfmts/${_bname}" ]; then
			update-binfmts --package "${PKGNAME}" --remove "${_bname}" "${_bin}"
		fi
	done
}

# {,un}import_binfmts: new installation style
import_binfmts() {
	for _fmt in $import_binfmts; do
		update-binfmts --import "$_fmt"
	done
}

unimport_binfmts() {
	for _fmt in $import_binfmts; do
		if [ -f "var/lib/binfmts/${_fmt}" ]; then
			update-binfmts --unimport "$_fmt"
		fi
	done
}

case "$ACTION" in
targets)
	echo "post-install pre-remove"
	;;
run)
	[ -x /usr/bin/update-binfmts ] || exit 0

	case "$TARGET" in
	post-install)
		if [ -n "${binfmts}" ]; then
			install_binfmts
		fi
		if [ -n "${import_binfmts}" ]; then
			import_binfmts
		fi
		;;
	pre-remove)
		if [ -n "${binfmts}" ]; then
			remove_binfmts
		fi
		if [ -n "${import_binfmts}" ]; then
			unimport_binfmts
		fi
		;;
	*)
		exit 1
		;;
	esac
	;;
*)
	exit 1
	;;
esac

exit 0
# end
# end
# end
