#!/bin/bash -ex

# Conf script for tklovz - leveraging TKLPatch to create
# OpenVZ templates from ISOs

# replace rsyslog with syslog-ng (for performance)
apt-get remove --purge -y rsyslog

# remove other unrequired packages
apt-get remove --purge -y libparted0debian1 di-live grub-pc grub-common hdparm acpid lvm2 webmin-lvm webmin-fdisk webmin-raid casper

# remove unrequired init scripts
cd /etc/init
rm -f console* control* hwclock* module* mount* network-interface* plymouth* procps* tty* udev* upstart* 

# install packages
apt-get update
apt-get install --force-yes -y gpgv
apt-get install -y quota syslog-ng 

#Stop syslog-ng service (started when installed)
service syslog-ng stop

# set some packages to manual install (so they aren't removed by apt-get autoremove). Not sure if they're all needed but they're only small
apt-get install whiptail watershed libdevmapper-event1.02.1 libdebconfclient0 libdebian-installer4 

# Disable confconsole - OVZ doesn't have a proper console
update-rc.d confconsole disable

# Hold mountall upstart
echo "mountall hold" | dpkg --set-selections
echo "upstart hold" | dpkg --set-selections
echo "ifupdown hold" | dpkg --set-selections

# Hold kernel metapackage
echo "linux-image-generic hold" | dpkg --set-selections

# Remove stuff not required
rm -r /boot/*
rm -r /lib/firmware/*
rm -r /lib/modules/*
rm /initrd.img
rm /vmlinuz

#Fix modprobe
rm /sbin/modprobe
ln -s /bin/true /sbin/modprobe

#Fix ssh
sed -i -e 's_oom never_#oom never_g' /etc/init/ssh.conf

# Clean packages
apt-get clean
#apt-get autoremove

# Remove package lists (regenerated with apt-get update)
rm /var/cache/apt/srcpkgcache.bin
rm /var/cache/apt/pkgcache.bin

# As of v11.2-1 OVZ templates use a subset of the default TKL firstboot scripts for all appliances
# The remaining firstboot inithooks are executed with the command 'init-ovz'
# Move the default firstboot scripts, recreate firstboot.d, move back non-interactive scripts (& set root pass - not needed at all in OVZ container)
cd /usr/lib/inithooks/
mv firstboot.d firstboot.d.orig
mkdir firstboot.d
cp firstboot.d.orig/.anchor firstboot.d/
mv firstboot.d.orig/10randomize-cronapt firstboot.d/
mv firstboot.d.orig/10regen-sshkeys firstboot.d/
mv firstboot.d.orig/15regen-sslcert firstboot.d/
rm firstboot.d.orig/30rootpass
mv firstboot.d.orig/50auto-apt-archive firstboot.d/
mv firstboot.d.orig/90delconf firstboot.d/
mv firstboot.d.orig/92etckeeper firstboot.d/

# disable some unnecessary boot scripts
update-rc.d -f ondemand remove

# Clear log files
> /etc/resolv.conf \
echo localhost > /etc/hostname \
> /var/log/messages; > /var/log/auth.log; > /var/log/kern.log; > /var/log/bootstrap.log; \
> /var/log/dpkg.log; > /var/log/syslog; > /var/log/daemon.log; > /var/log/apt/term.log; rm -f /var/log/*.0 /var/log/*.1
rm /dev/log