#!/bin/bash -eux
# Blatantly stolen from from https://raw.githubusercontent.com/StefanScherer/ubuntu-vm/my/script/cleanup-vcloud.sh
# Thanks Stefan!

CLEANUP_PAUSE=${CLEANUP_PAUSE:-0}
echo "==> Pausing for ${CLEANUP_PAUSE} seconds..."
sleep ${CLEANUP_PAUSE}

# Make sure udev does not block our network - http://6.ptmc.org/?p=164
echo "==> Cleaning up udev rules"
rm -rf /dev/.udev/
rm /lib/udev/rules.d/75-persistent-net-generator.rules

echo "==> Cleaning up leftover dhcp leases"
# Ubuntu 10.04
if [ -d "/var/lib/dhcp3" ]; then
    rm /var/lib/dhcp3/*
fi
# Ubuntu 12.04 & 14.04
if [ -d "/var/lib/dhcp" ]; then
    rm /var/lib/dhcp/*
fi 

if [ ! -d "/etc/dhcp3" ]; then
  if [ -d "/etc/dhcp" ]; then
    echo "Patching /etc/dhcp3 for vCloud"
    ln -s /etc/dhcp /etc/dhcp3
  fi
fi

echo "Writing a fixed eth0 entry to avoid delay on first boot in vCloud"
cat <<CFG | tee /etc/network/interfaces
auto lo
iface lo inet loopback
auto eth0
iface eth0 inet static
  address 192.168.66.111
        netmask 255.255.255.0
        gateway 192.168.66.1
        metric 0
CFG

echo "==> Removing network-manager (KB2042181)"
apt-get remove --purge network-manager

echo "==> Cleaning up tmp"
rm -rf /tmp/*

# Cleanup apt cache
apt-get -y autoremove --purge
apt-get -y clean
apt-get -y autoclean

echo "==> Installed packages"
dpkg --get-selections | grep -v deinstall

# Remove Bash history
unset HISTFILE
rm -f /root/.bash_history
rm -f /home/vagrant/.bash_history

# Clean up log files
find /var/log -type f | while read f; do echo -ne '' > $f; done;

export PREFIX="/sbin"

FileSystem=`grep ext /etc/mtab| awk -F" " '{ print $2 }'`

for i in $FileSystem
do
        echo $i
        number=`df -B 512 $i | awk -F" " '{print $3}' | grep -v Used`
        echo $number
        percent=$(echo "scale=0; $number * 98 / 100" | bc )
        echo $percent
        dd count=`echo $percent` if=/dev/zero of=`echo $i`/zf
        /bin/sync
        sleep 15
        rm -f $i/zf
done

VolumeGroup=`$PREFIX/vgdisplay | grep Name | awk -F" " '{ print $3 }'`

for j in $VolumeGroup
do
        echo $j
        $PREFIX/lvcreate -l `$PREFIX/vgdisplay $j | grep Free | awk -F" " '{ print $5 }'` -n zero $j
        if [ -e /dev/$j/zero ]; then
                cat /dev/zero > /dev/$j/zero
                /bin/sync
                sleep 15
                $PREFIX/lvremove -f /dev/$j/zero
        fi
done

# Make sure we wait until all the data is written to disk, otherwise
# Packer might quit too early before the large files are deleted
sync