#!/bin/sh

if [ $1 = "setup-start" ]; then

    # If the session user is a member of the sbuild group, make sure
    # that the chroot environment has the sbuild build directory
    # exists, and has the correct ownership permissions.

    if getent group $(id -G "${AUTH_USER}") | \
	sed -e 's/^\([^:]*\):.*$/\1/' | \
	grep -q '^sbuild$'; then

	if [ ! -d "${CHROOT_PATH}/build/${AUTH_USER}" ]; then
	    if [ "$AUTH_VERBOSITY" = "verbose" ]; then
		echo "Creating sbuild build directory: ${CHROOT_PATH}/build/${AUTH_USER}"
	    fi
	    mkdir -p "${CHROOT_PATH}/build/${AUTH_USER}"
	fi

	if [ "$AUTH_VERBOSITY" = "verbose" ]; then
	    echo "Setting ownership of ${CHROOT_PATH}/build/${AUTH_USER} to ${AUTH_USER}:sbuild"
	fi
	chown "${AUTH_USER}:sbuild" "${CHROOT_PATH}/build/${AUTH_USER}"

	if [ "$AUTH_VERBOSITY" = "verbose" ]; then
	    echo "Setting permissions of ${CHROOT_PATH}/build/${AUTH_USER} to 770"
	fi
	chmod 770 "${CHROOT_PATH}/build/${AUTH_USER}"

	if [ ! -d "${CHROOT_PATH}/var/lib/sbuild/srcdep-lock" ]; then
	    if [ "$AUTH_VERBOSITY" = "verbose" ]; then
		echo "Creating srcdep-lock directory: ${CHROOT_PATH}/var/lib/sbuild/srcdep-lock"
	    fi
	    mkdir -p "${CHROOT_PATH}/var/lib/sbuild/srcdep-lock"
	fi

	if [ "$AUTH_VERBOSITY" = "verbose" ]; then
	    echo "Setting ownership of ${CHROOT_PATH}/var/lib/sbuild to root:sbuild"
	fi
	chown -R root:sbuild "${CHROOT_PATH}/var/lib/sbuild"

	if [ "$AUTH_VERBOSITY" = "verbose" ]; then
	    echo "Setting permissions of ${CHROOT_PATH}/var/lib/sbuild to 02775"
	fi
	chmod -R 02775 "${CHROOT_PATH}/var/lib/sbuild"

    else

	if [ "$AUTH_VERBOSITY" = "verbose" ]; then
	    echo "User ${AUTH_USER} is not in group sbuild; skipping sbuild setup"
	fi

    fi

fi
