#!/bin/bash

set -e
set -u

DOCKER=docker
IMAGE_TAG=${IMAGE_TAG:-debian/sid/docker-builder}
ACNG_PORT=${ACNG_PORT:-3142}

CMD=${1:-}
shift


## misc helpers

fail() {
	echo >&2 "$@"
	exit 1
}

user_in_docker_group() {
	id -Gn | grep -q '\bdocker\b'
}

apt_cacher_ng_running() {
	command -v nc >/dev/null 2>&1 || return 1
	nc -z localhost $1
}


## docker helpers

docker_build() {
	local opts=()

	apt_cacher_ng_running $ACNG_PORT && \
		opts+=("--build-arg" "http_proxy=http://172.17.0.1:$ACNG_PORT")

	cd debian
	$DOCKER build \
	  "${opts[@]}" \
	  -t $IMAGE_TAG \
	  .
}

docker_run_as_user() {
	$DOCKER run -it --rm \
	  -u $(id -u):$(id -g) \
	  -v /etc/group:/etc/group:ro \
	  -v /etc/passwd:/etc/passwd:ro \
	  -v $(pwd)/..:/usr/src/ \
	  -w /usr/src/$(basename $(pwd)) \
	  $IMAGE_TAG \
	  "$@"
}

docker_run_as_root() {
	$DOCKER run -it --rm \
	  --privileged \
	  -v $(pwd)/..:/usr/src \
	  -w /usr/src/$(basename $(pwd)) \
	  $IMAGE_TAG \
	  "$@"
}


## main

test -d debian || \
	fail "No 'debian' directory. Please run from the root of the source tree"

user_in_docker_group || \
	DOCKER='sudo docker'


case "$CMD" in
	(build)
		docker_build ;;
	(run-user)
		docker_run_as_user "$@" ;;
	(run-root)
		docker_run_as_root "$@" ;;
	(*)
		fail "Usage: $(basename $0) build | run-user [CMD] | run-root [CMD]" ;;
esac
