#!/bin/bash -e

. $(dirname $0)/mbd-common.sh
. "${MBD_REPCONFIGFILE}"
. "${MBD_BLDCONFIGFILE}"

mbd_opt_init "Mini-buildd: Setup base chroots (root only)."
mbd_opt_add "f" "Force fresh setup (i.e., delete old setup first)."
mbd_opt_add "d" "Delete existing setup."
mbd_opt_parse "$@"

if ${mbd_defer}; then
	${MBD_LOG} -s "W: Configuration deferred, skipping."
	exit 0
fi

CHROOT_FS="ext2"

mbdGetChrootPersonality()
{
	local arch="${1}"
	case ${arch} in
		i386)
			echo -n "linux32"
			;;
		*)
			echo -n "linux"
			;;
	esac
}

mbdCheckUser root

# Always remove obsoleted (since 0.8.15) tainting of /etc/schroot/schroot.conf, if found.
mbdDeleteMarkedConfig()
{
	local MBD_CONFIG_MARK="# MINI-BUILDD AUTOGENERATION MARK"
	local conffile="/etc/schroot/schroot.conf"

	local marks=$(grep -n -m 2 "${MBD_CONFIG_MARK}" "${conffile}" | cut -d: -f1)
	local m0=$(echo ${marks} | cut -d" " -f1)
	local m1=$(echo ${marks} | cut -d" " -f2)

	if [ -n "${m0}" -a -n "${m1}" ]; then
		sed "${m0},${m1}d" "${conffile}" >"${conffile}.tmp"
		mv "${conffile}.tmp" "${conffile}"
		echo "I: Removed obsoleted marked config from ${conffile}."
	fi
}
mbdDeleteMarkedConfig

# Write schroot config file header
echo -e "# Auto-generated by ${0} on $(date).\n" >"${MBD_SCHROOTCONFIGFILE}"

MBD_TMP_MNTPOINT=$(mktemp -d /tmp/mini-buildd.XXXXXX)
trap "rmdir ${MBD_TMP_MNTPOINT}" EXIT

# Check/prepare chroots for all dists.
for dist in $(mbdD2SList "${mbd_dists}"); do
	for arch in $(mbdD2SList "${mbd_archs}"); do
		# Are we responsible for that arch?
		MBD_TMP_BLDHOST="mbd_bldhost_${arch}"
		if [ "${mbd_bldhost}" = "${!MBD_TMP_BLDHOST}" ]; then
			MBD_TMP_CHROOT="mbd-${dist}-${mbd_id}-${arch}";
			MBD_TMP_CHROOT_EXPERIMENTAL="mbd-${dist}-${mbd_id}-experimental-${arch}";
			MBD_TMP_DEV="/dev/$(mbdLvmVgName)/${MBD_TMP_CHROOT}"
			MBD_TMP_CHROOT_PERSONALITY=$(mbdGetChrootPersonality ${arch});

			if (mbd_opt_given f || mbd_opt_given d) && lvdisplay | grep -q "${MBD_TMP_CHROOT}"; then
				${MBD_LOG} -s "I: LV ${MBD_TMP_CHROOT}: Forcing removal: $(lvremove --force "${MBD_TMP_DEV}" 2>&1)"
			fi

			if ! mbd_opt_given d; then
				if lvdisplay | grep -q "${MBD_TMP_CHROOT}"; then
					${MBD_LOG} -s "I: LV ${MBD_TMP_CHROOT} exists, leaving alone."
				else
					${MBD_LOG} -s "I: Setting up chroot ${MBD_TMP_CHROOT}..."

					MBD_TMP_BASESRC=$(mbdGetSrcVar ${dist} base ${arch})
					MBD_TMP_MIRROR=$(echo "${!MBD_TMP_BASESRC}" | cut -d' ' -f1)
					${MBD_LOG} -s "I: Found mirror for ${dist}(${arch}): ${MBD_TMP_MIRROR}"

					(
						mbdAptEnv
						if lvcreate -L 4G -n "${MBD_TMP_CHROOT}" "$(mbdLvmVgName)" &&
							mkfs.${CHROOT_FS} "${MBD_TMP_DEV}" &&
							mount -v -t${CHROOT_FS} "${MBD_TMP_DEV}" "${MBD_TMP_MNTPOINT}" &&
							debootstrap --variant=buildd --arch ${arch} --include=apt "${dist}" "${MBD_TMP_MNTPOINT}" "${MBD_TMP_MIRROR}" &&
							umount -v "${MBD_TMP_MNTPOINT}"; then
							echo "I: LV ${MBD_TMP_CHROOT} created successfully."
						else
							echo "E: Failed to create LV ${MBD_TMP_CHROOT}; rerun ${0} as root any time to retry; rewinding..."
							umount -v "${MBD_TMP_MNTPOINT}" || true
							lvremove --force "${MBD_TMP_DEV}" || true
						fi
					) 2>&1 | ${MBD_LOG} -s
				fi
				# We need two configs to be able to distinguish experimental for sources setup (does not work with aliases).
				for chroot_name in ${MBD_TMP_CHROOT} ${MBD_TMP_CHROOT_EXPERIMENTAL}; do
					cat <<EOF >>"${MBD_SCHROOTCONFIGFILE}"
[${chroot_name}]
type=lvm-snapshot
description=Mini-Buildd ${MBD_TMP_CHROOT} snapshot chroot
groups=sbuild
users=mini-buildd
root-groups=sbuild
root-users=mini-buildd
source-root-users=mini-buildd
device=${MBD_TMP_DEV}
mount-options=-t ${CHROOT_FS} -o noatime,user_xattr
lvm-snapshot-options=--size 4G
personality=${MBD_TMP_CHROOT_PERSONALITY}

EOF
				done
			fi
		fi
	done
done

if ! mbd_opt_given d; then
	${MBD_LOG} -s "I: ${MBD_SCHROOTCONFIGFILE} updated."
	# Trigger a -bld update
	su - mini-buildd -c "${MBD_LIB}/mbd-update-bld"
else
	${MBD_LOG} -s "I: Purging schroot config: $(rm -v ${MBD_SCHROOTCONFIGFILE} 2>&1)"
fi
