#!/bin/bash
set -e

SELFDIR="`dirname \"$0\"`"
SELFDIR="`cd \"$SELFDIR\" && pwd`"
source "$SELFDIR/internal/lib/library.sh"
source "$SELFDIR/internal/lib/distro_info.sh"

WORK_DIR=
CACHE_DIR=
DISTRIBUTIONS="$DEFAULT_DISTROS"
ARCHITECTURES="i386 amd64"
ARGV=

function usage()
{
	echo "Usage: ./shell [OPTIONS] <TASK NAMES...>"
	echo "Open a shell in a build box container."
	echo
	echo "Required options:"
	echo "  -c DIR     Path to cache directory"
	echo
	echo "Optional options:"
	echo "  -w DIR     Path to work directory (for temporary files)"
	echo "  -d NAMES   Build only for given distributions. This is a space-separated list"
	echo "             of distribution names."
	echo "             Default: $DEFAULT_DISTROS"
	echo "  -a NAMES   Build only for given architectures. This is a space-separated list"
	echo "             of architecture names."
	echo "             Default: $ARCHITECTURES"
	echo "  -h         Show usage"
}

function parse_options()
{
	local OPTIND=1
	local opt
	while getopts "c:w:d:a:h" opt; do
		case "$opt" in
		c)
			CACHE_DIR="$OPTARG"
			;;
		w)
			WORK_DIR="$OPTARG"
			;;
		d)
			DISTRIBUTIONS="$OPTARG"
			;;
		a)
			ARCHITECTURES="$OPTARG"
			;;
		h)
			usage
			exit
			;;
		*)
			return 1
			;;
		esac
	done

	(( OPTIND -= 1 )) || true
	shift $OPTIND || true
	ARGV=("$@")

	if [[ "$CACHE_DIR" = "" ]]; then
		echo "ERROR: please specify a cache directory with -c."
		exit 1
	fi
}

parse_options "$@"

DOCKER_OPTIONS=()
CACHE_DIR="`absolute_path \"$CACHE_DIR\"`"
run mkdir -p "$CACHE_DIR"
run mkdir -p "$CACHE_DIR/pbuilder/ccache"

if [[ "$WORK_DIR" != "" ]]; then
	WORK_DIR="`absolute_path \"$WORK_DIR\"`"
	run mkdir -p "$WORK_DIR"
	DOCKER_OPTIONS+=(-v "/work:$WORK_DIR")
fi

echo "+ Initializing ccache directory"
verbose_run docker run \
	--rm -t -i \
	-v "$SELFDIR:/system:ro" \
	-v "$CACHE_DIR:/cache" \
	-e "DISTRIBUTIONS=$DISTRIBUTIONS" \
	-e "ARCHITECTURES=$ARCHITECTURES" \
	-e "APP_UID=`/usr/bin/id -u`" \
	-e "APP_GID=`/usr/bin/id -g`" \
	phusion/passenger_apt_automation_buildbox \
	/system/internal/scripts/inituidgid.sh \
	/system/internal/scripts/initccache.sh

echo "-------- Entering Docker container --------"
exec docker run \
	--rm -t -i \
	--privileged \
	-v "$SELFDIR:/system:ro" \
	-v "$CACHE_DIR:/cache" \
	-v "$CACHE_DIR/pbuilder:/var/cache/pbuilder" \
	-e "DISTRIBUTIONS=$DISTRIBUTIONS" \
	-e "ARCHITECTURES=$ARCHITECTURES" \
	-e "APP_UID=`/usr/bin/id -u`" \
	-e "APP_GID=`/usr/bin/id -g`" \
	-e "LC_CTYPE=C.UTF-8" \
	"${DOCKER_OPTIONS[@]}" \
	phusion/passenger_apt_automation_buildbox \
	/sbin/my_init --quiet --skip-runit --skip-startup-files -- \
	/system/internal/scripts/inituidgid.sh \
	/system/internal/shell/preinit.sh \
	/sbin/setuser app \
	/bin/bash -l
