#!/bin/bash

set -e
set -u

# Alternative:
# shrink VDI image by writting to a new (unfragmented) image
# target VDI needs to have proper partition table and MBR
# simplest solution: clonezilla

# No deferencing of symbolic links should be done
# since otherwise might not be found by VirtualBox
#vdifile=$(readlink -f $1)
# Just asssume that we are providing full pathname
vdifile="$1"

if [ -z "$vdifile" ] || [ ! -e "$vdifile" ] || [ "${vdifile:0:1}" != "/" ] ; then
  echo "You need to provide full pathname to an existing VDI file."
  exit 1
fi

wdir=$(mktemp -d -t compactvdi.XXXXXX)

cd $wdir
# make mount points
mkdir -p vbdev vbmnt
# get access to disks inside the VDIs
vdfuse -f "$vdifile" vbdev
# mount partitition (for now only support one)
mount -o loop vbdev/Partition1 vbmnt

# remove cruft
#xapian indices
find vbmnt/var/ -wholename '*xapian*.DB' -delete
# package cache
find vbmnt/var/cache/apt/archives/ -name '*.deb' -delete
rm -f vbmnt/var/cache/apt/*.bin
rm -f vbmnt/var/cache/debconf/*-old
# device files -- udev restores them
rm -rf vbmnt/dev/*

# tmp
rm -rf vbmnt/tmp/*
# log files
find vbmnt/var/log -type f -delete
# apt lists
find vbmnt/var/lib/apt -type f -name '*debian*' -o -type f -name '*list*' | xargs -r rm
# user data
# cannot clean all root stuff, because it also contains useful thing (e.g. git setup)
rm -f vbmnt/root/.*history
rm -f vbmnt/home/brain/.*history vbmnt/home/brain/nd*

# unmount filesystem
umount vbmnt
# zero out empty space
zerofree -v vbdev/Partition1
# close whole VDI
umount vbdev

# compact VDI
# THIS NEEDS TO BE DONE ON A VDI THAT IS REGISTERED WITH VIRTUALBOX
sudo -u "$SUDO_USER" VBoxManage modifyhd "$vdifile" --compact

# cleanup
echo "I: Cleaning up after VDI compact operation"
rm -rf $wdir
