#!/bin/bash -ex
# Author: Alon Swartz <alon@turnkeylinux.org> (c) 2012-2013

install() {
    apt-get update
    DEBIAN_FRONTEND=noninteractive apt-get -y \
        -o DPkg::Options::=--force-confdef \
        -o DPkg::Options::=--force-confold \
        install $@
}

# install required packages
install quota

# remove kernel
ARCH=$(dpkg --print-architecture)
case "$ARCH" in
    "i386")
        OLD_META_KERNEL="linux-image-686";
        ;;
    "amd64")
        OLD_META_KERNEL="linux-image-amd64";
        ;;
    *)
        fatal "non-supported architecture: $ARCH";
        ;;
esac
OLD_KERNEL=$(echo /boot/vmlinuz-* | sed 's|/boot/vmlinuz-|linux-image-|')
OLD_KERNEL_VER=$(echo /boot/vmlinuz-* | sed 's|/boot/vmlinuz-||')

mv /usr/sbin/update-grub /usr/sbin/update-grub.orig
ln -s /bin/true /usr/sbin/update-grub

debconf-set-selections << EOF
$OLD_KERNEL $OLD_KERNEL/prerm/removing-running-kernel-$OLD_KERNEL_VER boolean false
EOF
DEBIAN_FRONTEND=noninteractive apt-get -y purge $OLD_META_KERNEL $OLD_KERNEL

rm /usr/sbin/update-grub
mv /usr/sbin/update-grub.orig /usr/sbin/update-grub

# remove resolvconf
rm -rf /var/run/resolvconf
dpkg --purge resolvconf
rm -f /etc/resolv.conf*
touch /etc/resolv.conf

# remove ntp daemon
dpkg --purge ntp

# disable ttys, enable openvz_console
sed -i '/^[^#]:[2-5]*:respawn:*/s/^/# /' /etc/inittab
echo "1:2345:respawn:/sbin/getty 38400 tty1" >> /etc/inittab

update-rc.d -f confconsole disable

# modprobe doesn't work in openvz
mv /sbin/modprobe /sbin/modprobe.orig
ln -s /bin/true /sbin/modprobe

# root password is set outside of container
chmod -x /usr/lib/inithooks/firstboot.d/30rootpass

# redirect inithook output (preseeded headless deployment)
sed -i '/REDIRECT_OUTPUT/ s/=.*/=true/g' /etc/default/inithooks

