#!/bin/bash

set -e
umask 022

error() {
	echo $* >&2
	exit 1
}

log() {
	echo $* >/dev/null
}

command_prepare_active() {
	[ "$1" ] || error "Missing queue path"
	queue="$1"
	shift 1
	cat >> "$root"/etc/apt/sources.list <<EOF
deb file:///manual/ ./
deb-src copy:///manual/ ./
EOF
	man="$root"/manual
	mkdir "$man"
	mount --bind -o ro "$queue" "$man"
	apt "$root" update
}

apt() {
        chroot="$1"
        shift
        command chroot "$chroot" apt-get "$@"
}

main() {
	[ "$1" ] || error "No command specified."
	command="$1"
	shift

	case "$command" in
		help)
		command_help
		return
		;;
	esac

	[ "$1" ] || error "No root specified."
	root="$1"
	shift
	[ -d "$root" ] || log "Root $root doesn't exist. Will be created."

	case "$command" in
		prepare-active)
		command_prepare_active "$@"
		;;
		*)
		error "Unknown command. Exiting."
	esac
}

main "$@"
