#!/bin/bash

# This is a modified version of /usr/share/lxc/templates/lxc-debian
# that comes with Ubuntu 13.04 changed to suit vagrant-lxc needs

set -e

if [ -r /etc/default/lxc ]; then
    . /etc/default/lxc
fi

SUITE=${SUITE:-wheezy}
MIRROR=${MIRROR:-http://ftp.debian.org/debian}

configure_debian()
{
    rootfs=$1
    hostname=$2
    release=$2

    # squeeze only has /dev/tty and /dev/tty0 by default,
    # therefore creating missing device nodes for tty1-4.
    for tty in $(seq 1 4); do
        if [ ! -e $rootfs/dev/tty$tty ]; then
            mknod $rootfs/dev/tty$tty c 4 $tty
        fi
    done

    # configure the inittab
    cat <<EOF > $rootfs/etc/inittab
id:3:initdefault:
si::sysinit:/etc/init.d/rcS
l0:0:wait:/etc/init.d/rc 0
l1:1:wait:/etc/init.d/rc 1
l2:2:wait:/etc/init.d/rc 2
l3:3:wait:/etc/init.d/rc 3
l4:4:wait:/etc/init.d/rc 4
l5:5:wait:/etc/init.d/rc 5
l6:6:wait:/etc/init.d/rc 6
# Normally not reached, but fallthrough in case of emergency.
z6:6:respawn:/sbin/sulogin
1:2345:respawn:/sbin/getty 38400 console
#c1:12345:respawn:/sbin/getty 38400 tty1 linux
c2:12345:respawn:/sbin/getty 38400 tty2 linux
c3:12345:respawn:/sbin/getty 38400 tty3 linux
c4:12345:respawn:/sbin/getty 38400 tty4 linux
p6::ctrlaltdel:/sbin/init 6
p0::powerfail:/sbin/init 0
EOF

    # disable selinux in debian
    mkdir -p $rootfs/selinux
    echo 0 > $rootfs/selinux/enforce

    # configure the network using the dhcp
    cat <<EOF > $rootfs/etc/network/interfaces
auto lo
iface lo inet loopback

auto eth0
iface eth0 inet dhcp
EOF

    # set the hostname
    cat <<EOF > $rootfs/etc/hostname
$hostname
EOF

    # set minimal hosts
    cat <<EOF > $rootfs/etc/hosts
127.0.0.1   localhost
127.0.1.1   $hostname

# The following lines are desirable for IPv6 capable hosts
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
ff02::3 ip6-allhosts
EOF

    # set default locale
    cat <<EOF > $rootfs/etc/locale.gen
en_US.UTF-8 UTF-8
EOF
    echo "default locale set to en_US.UTF-8 UTF-8"
    chroot $rootfs locale-gen 'en_US.UTF-8' > /dev/null 2>&1
    chroot $rootfs update-locale LANG='en_US.UTF-8'
    echo 'update-locale done'

    # remove pointless services in a container
    chroot $rootfs /usr/sbin/update-rc.d -f checkroot.sh remove
    chroot $rootfs /usr/sbin/update-rc.d -f umountfs remove
    chroot $rootfs /usr/sbin/update-rc.d -f hwclock.sh remove
    chroot $rootfs /usr/sbin/update-rc.d -f hwclockfirst.sh remove

    echo "root:vagrant" | chroot $rootfs chpasswd

    if ! (grep -q vagrant $rootfs/etc/passwd); then
      chroot $rootfs useradd --create-home -s /bin/bash vagrant
      echo "vagrant:vagrant" | chroot $rootfs chpasswd
      chroot $rootfs adduser vagrant sudo >/dev/null 2>&1 || true
      chroot $rootfs cp /etc/sudoers /etc/sudoers.orig >/dev/null 2>&1 || true
      chroot $rootfs sed -i -e \
          's/%sudo\s\+ALL=(ALL\(:ALL\)\?)\s\+ALL/%sudo ALL=NOPASSWD:ALL/g' \
          /etc/sudoers >/dev/null 2>&1 || true
    fi

    return 0
}

cleanup()
{
    rm -rf ${cache}/partial
    rm -rf ${cache}/rootfs
}

add_ssh_key()
{
    user=$1

    if [ -n "$auth_key" -a -f "$auth_key" ]; then
        u_path="/home/${user}/.ssh"
        root_u_path="$rootfs/$u_path"

        mkdir -p $root_u_path
        cp $auth_key "$root_u_path/authorized_keys"
        chroot $rootfs chown -R ${user}: "$u_path"

        echo "Inserted SSH public key from $auth_key into /home/${user}/.ssh/authorized_keys"
    fi
}

disable_tmp_cleanup() {
    rootfs=$1
    chroot $rootfs /usr/sbin/update-rc.d -f checkroot-bootclean.sh remove
    chroot $rootfs /usr/sbin/update-rc.d -f mountall-bootclean.sh remove
    chroot $rootfs /usr/sbin/update-rc.d -f mountnfs-bootclean.sh remove
}

release=wheezy  # Default to the last Debian stable release

arch=$(uname -m)

# Code taken from debootstrap
if [ -x /usr/bin/dpkg ] && /usr/bin/dpkg --print-architecture >/dev/null 2>&1; then
    arch=`/usr/bin/dpkg --print-architecture`
elif type udpkg >/dev/null 2>&1 && udpkg --print-architecture >/dev/null 2>&1; then
    arch=`/usr/bin/udpkg --print-architecture`
else
    arch=$(uname -m)
    if [ "$arch" = "i686" ]; then
        arch="i386"
    elif [ "$arch" = "x86_64" ]; then
        arch="amd64"
    elif [ "$arch" = "armv7l" ]; then
        arch="armel"
    fi
fi

if [ "$(id -u)" != "0" ]; then
    echo "This script should be run as 'root'"
    exit 1
fi

declare cache=`readlink -f .` \
        arch=$1 \
        release=$2 \
        auth_key=$3

# detect rootfs
cache=`readlink -f .`
rootfs="${cache}/rootfs"

configure_debian $rootfs $release
if [ $? -ne 0 ]; then
    echo "failed to configure debian $release for a container"
    exit 1
fi

add_ssh_key vagrant

# vagrant and / or plugins might mount some shared folders under /tmp by default
# (like puppet manifests) and we need to make sure no shared folder gets its
# contents removed because of it. For more information, please check:
#   https://github.com/fgrehm/vagrant-lxc/issues/68
disable_tmp_cleanup $rootfs

echo ""
echo "##"
echo "# The default user is 'vagrant' with password 'vagrant'!"
echo "# Use the 'sudo' command to run tasks as root in the container."
echo "##"
echo ""