#!/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 vdifile=$(readlink -f $1) if [ -z "$vdifile" ]; then echo "You need to provide a 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 # 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*' -delete # 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 rm -rf $wdir