#!/bin/sh

## live-build(7) - System Build Scripts
## Copyright (C) 2020 The Debian Live team
##
## This program comes with ABSOLUTELY NO WARRANTY; for details see COPYING.
## This is free software, and you are welcome to redistribute it
## under certain conditions; see COPYING for details.


set -e

# Including common functions
[ -e "${LIVE_BUILD}/scripts/build.sh" ] && . "${LIVE_BUILD}/scripts/build.sh" || . /usr/lib/live/build.sh

# Setting static variables
DESCRIPTION="Prep chroot"
USAGE="${PROGRAM} {install|remove} {all|all-except-archives|\"HELPERS\"} [MODE[ MODE..]] [--force]"

# Processing arguments and configuration files
Init_config_data "${@}"

# Requiring stage file
Require_stagefiles config bootstrap

ACTION="${1}"
HELPERS="${2}"
shift 2

if ! In_list "${ACTION}" install remove; then
	Echo_error "Invalid action parameter"
	exit 1
fi

if [ -z "${HELPERS}" ]; then
	Echo_error "You must specify which helpers to run"
	exit 1
fi

ARCHIVES_PASS=""
APT_ACTION="${ACTION}"

MODES="mode-archives-chroot \
       mode-archives-binary \
       mode-archives-source \
       mode-apt-install-binary"

while In_list "${1}" $MODES; do
	case "${1}" in
		mode-archives-chroot)
			ARCHIVES_PASS="chroot"
			;;
		mode-archives-binary)
			ARCHIVES_PASS="binary"
			;;
		mode-archives-source)
			ARCHIVES_PASS="source"
			;;
		mode-apt-install-binary)
			APT_ACTION="install-binary"
			;;
		*)
			Echo_error "Internal failure, case not covered"
			exit 1
			;;
	esac
	shift
done

# Default set, EXCLUDING 'archives'
DEFAULT_HELPERS="devpts proc selinuxfs sysfs debianchroot dpkg tmpfs sysv-rc hosts resolv hostname apt"

case "${HELPERS}" in
	all)
		HELPERS="${DEFAULT_HELPERS} archives"
		;;
	all-except-archives)
		HELPERS="${DEFAULT_HELPERS}"
		;;
	*)
		# Support both comma and space separation
		# Support with and without 'chroot_' script filename prefix
		HELPERS="$(echo "${HELPERS}" | sed -e 's|,| |g' -e 's|^chroot_||g')"
		;;
esac

if In_list "prep" ${HELPERS}; then
	Echo_error "Recursive!"
	exit 1
fi

if In_list "archives" ${HELPERS} && [ -z "${ARCHIVES_PASS}" ]; then
	Echo_error "Use of the archives component through chroot_prep requires specifying a mode-archives-* mode"
	exit 1
fi

if In_list "archives" ${HELPERS} && ! Stagefile_exists bootstrap; then
	Echo_warning "The 'archives' helper is selected, but the bootstrap stage has not completed."
fi

if [ "${ACTION}" = "remove" ]; then
	HELPERS_REVERSED=""
	for HELPER in $HELPERS; do
		HELPERS_REVERSED="${HELPER}${HELPERS_REVERSED:+ $HELPERS_REVERSED}"
	done
	HELPERS="${HELPERS_REVERSED}"
fi

for HELPER in $HELPERS; do
	case "${HELPER}" in
		archives)
			lb "chroot_${HELPER}" "${ARCHIVES_PASS}" "${ACTION}" "${@}"
			;;
		apt)
			lb "chroot_${HELPER}" "${APT_ACTION}" "${@}"
			;;
		*)
			lb "chroot_${HELPER}" "${ACTION}" "${@}"
			;;
	esac
done
