#!/bin/sh

## live-build(7) - System Build Scripts
## Copyright (C) 2006-2012 Daniel Baumann <daniel@debian.org>
##
## 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
( . "${LIVE_BUILD}/scripts/build.sh" > /dev/null 2>&1 || true ) || . /usr/lib/live/build.sh

# Setting static variables
DESCRIPTION="$(Echo 'execute hooks in chroot (early stage)')"
HELP=""
USAGE="${PROGRAM} [--force]"

Arguments "${@}"

# Reading configuration files
Read_conffiles config/all config/common config/bootstrap config/chroot config/binary config/source
Set_defaults

Echo_message "Begin executing early chroot hooks..."

# Requiring stage file
Require_stagefile .build/config .build/bootstrap

# Checking stage file
Check_stagefile .build/chroot_early_hooks

# Checking lock file
Check_lockfile .lock

# Creating lock file
Create_lockfile .lock

## Processing local hooks
if Find_files config/hooks/*.chroot_early
then
	# Restoring cache
	Restore_cache cache/packages.chroot

	for _HOOK in config/hooks/*.chroot_early
	do
		# Copying hook
		cp "${_HOOK}" chroot/root

		# Making hook executable
		if [ ! -x chroot/root/"$(basename ${_HOOK})" ]
		then
			chmod +x chroot/root/"$(basename ${_HOOK})"
		fi

		# Executing hook
		Chroot chroot "/root/$(basename ${_HOOK})" || { Echo_error "${_HOOK} failed (exit non-zero). You should check for errors."; exit 1 ;}

		# Removing hook
		rm -f chroot/root/"$(basename ${_HOOK})"
	done

	# Saving cache
	Save_cache cache/packages.chroot

	# Creating stage file
	Create_stagefile .build/chroot_early_hooks
fi
