#!/bin/sh
#
# Script to generate a minimal chroot environment with Oracle (Sun) Java
# support to allow for Java programs to run in a chroot.  Also includes
# support for C#, python3, lua, and scala.
#
# This script downloads and installs an Ubuntu base system.
# Minimum requirements: a Linux system with glibc >= 2.3, wget, ar and
# a POSIX shell in /bin/sh. About 610 MB disk space is needed. It must
# be run as root and will install the debootstrap package.
#
# Part of the DOMjudge Programming Contest Jury System and licenced
# under the GNU GPL. See README and COPYING for details.

# Abort when a single command fails:
set -e

# Read command-line parameters:
CHROOTDIR=$1
ARCH=$2

# List of possible architectures to install chroot for:
ARCHLIST="amd64,armel,i386,ia64,mips,mipsel,powerpc,s390,sparc"

# Packages to include during bootstrap process (comma separated):
INCLUDEDEBS=""

# Packages to install after upgrade (space separated):
INSTALLDEBS="mono-mcs mono-gmcs mono-dmcs lua5.2 python3"
# The url for scala(should point to the version you want)
SCALAPKG="http://www.scala-lang.org/downloads/distrib/files/scala-2.10.2.tgz"

# Packages to remove after upgrade (space separated):
REMOVEDEBS=""

# Ubuntu mirror, modify to match closest mirror
DEBMIRROR="http://us.archive.ubuntu.com./ubuntu/"
DEBOOTDEB="debootstrap_1.0.46_all.deb"
# "$DEBMIRROR/pool/main/d/debootstrap/${DEBOOTDEB}"
CODENAME="precise"

# A local caching proxy to use for debian packages(Typically an install of aptcacher-ng)
#DEBPROXY="http://aptcacher-ng.example.com:3142/"
DEBPROXY=""

# To prevent (libc6) upgrade questions:
export DEBIAN_FRONTEND=noninteractive

usage()
{
    echo "Usage: $0 <chrootdir> <architecture>"
    echo "Creates a chroot environment with Oracle (Sun) Java support using the"
    echo "Debian GNU/Linux distribution."
    echo
    echo "This script must be run as root, <chrootdir> the non-existing target"
    echo "location of the chroot and <architecture> one of the following:"
    echo "$ARCHLIST"
}

error()
{
    echo "Error: $@"
    echo
    usage
    exit 1
}

if [ `id -u` != 0 ]; then
    echo "Warning: you probably need to run this program as root."
fi

[ -z "$CHROOTDIR" ] && error "No installation directory given."
[ -z "$ARCH" ]      && error "No architecture given."
[ -e "$CHROOTDIR" ] && error "'$CHROOTDIR' already exists, remove manually."

mkdir -p "$CHROOTDIR"
cd "$CHROOTDIR"
CHROOTDIR="$PWD"

if [ ! -x /usr/sbin/debootstrap ]; then
	if [ -f /etc/debian_version ]; then

		cd /
		apt-get install debootstrap

	else
		mkdir "$CHROOTDIR/debootstrap"
		cd "$CHROOTDIR/debootstrap"

		wget "$DEBMIRROR/pool/main/d/debootstrap/${DEBOOTDEB}"

		ar -x "$DEBOOTDEB"
		cd /
		zcat "$CHROOTDIR/debootstrap/data.tar.gz" | tar xv

		rm -rf "$CHROOTDIR/debootstrap"
	fi
fi

INCLUDEOPT=""
if [ -n "$INCLUDEDEBS" ]; then
	INCLUDEOPT="--include=$INCLUDEDEBS"
fi
EXCLUDEOPT=""
if [ -n "$EXCLUDEDEBS" ]; then
	EXCLUDEOPT="--exclude=$EXCLUDEDEBS"
fi

BOOTSTRAP_COMMAND="/usr/sbin/debootstrap"
if [ -n "$DEBPROXY" ]; then
    BOOTSTRAP_COMMAND="http_proxy=\"$DEBPROXY\" $BOOTSTRAP_COMMAND"
fi

echo "Running debootstrap to install base system, this may take a while..."

$BOOTSTRAP_COMMAND $INCLUDEOPT $EXCLUDEOPT \
	--variant=minbase --arch "$ARCH" $CODENAME "$CHROOTDIR" "$DEBMIRROR"

rm -f "$CHROOTDIR/etc/resolv.conf"
cp /etc/resolv.conf /etc/hostname "$CHROOTDIR/etc" || true

cat > "$CHROOTDIR/etc/apt/sources.list" <<EOF
deb $DEBMIRROR precise main
deb $DEBMIRROR precise universe
deb $DEBMIRROR precise-updates main
deb $DEBMIRROR precise-updates universe
deb $DEBMIRROR precise-security main
deb $DEBMIRROR precise-security universe
EOF

cat > "$CHROOTDIR/etc/apt/apt.conf" <<EOF
APT::Get::Assume-Yes "true";
APT::Get::Force-Yes "false";
APT::Get::Purge "true";
APT::Install-Recommends "false";
Acquire::Retries "3";
Acquire::PDiffs "false";
EOF

# Add apt proxy settings if desired
if [ -n "$DEBPROXY" ]; then
    echo "Acquire::http::Proxy \"$DEBPROXY\"" >> "$CHROOTDIR/etc/apt/apt.conf"
fi

mount -t proc proc "$CHROOTDIR/proc"

# Required for some warning messages about writing to log files
mount --bind /dev/pts "$CHROOTDIR/dev/pts"

# Prevent perl locale warnings in the chroot:
export LC_ALL=C

chroot "$CHROOTDIR" /bin/sh -c debconf-set-selections <<EOF
passwd	passwd/root-password-crypted	password	
passwd	passwd/user-password-crypted	password	
passwd	passwd/root-password		password	
passwd	passwd/root-password-again	password	
passwd	passwd/user-password-again	password	
passwd	passwd/user-password		password	
passwd	passwd/shadow			boolean	true
passwd	passwd/username-bad		note	
passwd	passwd/password-mismatch	note	
passwd	passwd/username			string	
passwd	passwd/make-user		boolean	true
passwd	passwd/md5			boolean	false
passwd	passwd/user-fullname		string	
passwd	passwd/user-uid			string	
passwd	passwd/password-empty		note	
debconf	debconf/priority	select	high
debconf	debconf/frontend	select	Noninteractive
locales	locales/locales_to_be_generated	multiselect	
locales	locales/default_environment_locale	select	None

# Oracle-java7-installer license agreement
debconf shared/accepted-oracle-license-v1-1 select true
debconf shared/accepted-oracle-license-v1-1 seen true
EOF

# Disable upstart init scripts(so upgrades work), we don't need to actually run
# any services in the chroot, so this is fine.
# Refer to: http://ubuntuforums.org/showthread.php?t=1326721
chroot "$CHROOTDIR" /bin/sh -c "dpkg-divert --local --rename --add /sbin/initctl"
chroot "$CHROOTDIR" /bin/sh -c "ln -s /bin/true /sbin/initctl"

# Upgrade the system, and install/remove packages as desired
chroot "$CHROOTDIR" /bin/sh -c "apt-get update && apt-get dist-upgrade"
chroot "$CHROOTDIR" /bin/sh -c "apt-get clean"
chroot "$CHROOTDIR" /bin/sh -c "apt-get install $INSTALLDEBS"

# Install (oracle) java
chroot "$CHROOTDIR" /bin/sh -c "apt-get install python-software-properties"
chroot "$CHROOTDIR" /bin/sh -c "apt-add-repository -y ppa:webupd8team/java"
chroot "$CHROOTDIR" /bin/sh -c "apt-get update"
chroot "$CHROOTDIR" /bin/sh -c "apt-get install oracle-java7-installer"

# Install scala(in /usr/local so it is on the path)
mkdir -p "$CHROOTDIR/usr/local"
curl $SCALAPKG | tar xzf - --no-same-owner --strip-components=1 -C "$CHROOTDIR/usr/local"
chmod +x "$CHROOTDIR"/usr/local/bin/*

# Do some cleanup of the chroot
chroot "$CHROOTDIR" /bin/sh -c "apt-get remove --purge $REMOVEDEBS"
chroot "$CHROOTDIR" /bin/sh -c "apt-get autoremove --purge"
chroot "$CHROOTDIR" /bin/sh -c "apt-get clean"

# Remove unnecessary setuid bits
chroot "$CHROOTDIR" /bin/sh -c "chmod a-s /usr/bin/wall /usr/bin/newgrp \
	/usr/bin/chage /usr/bin/chfn /usr/bin/chsh /usr/bin/expiry \
	/usr/bin/gpasswd /usr/bin/passwd /usr/lib/pt_chown \
	/bin/su /bin/mount /bin/umount /sbin/unix_chkpwd"

# Copy passwd file from host, necessary for python
cp /etc/passwd "$CHROOTDIR/etc/passwd"

# Disable root account
sed -i "s/^root::/root:*:/" "$CHROOTDIR/etc/shadow"

umount "$CHROOTDIR/dev/pts"
umount "$CHROOTDIR/proc"

exit 0
