#!/bin/bash
set -euo pipefail

if [[ $# < 2 ]]; then
    echo "Usage: $0 DISK ISO"
    echo "e.g. $0 /dev/sdd ~/isos/xubuntu-14.04.4-desktop-amd64.iso"
    exit 1
fi

disk=$1
iso=$2

# Make sure you are member of ``disk``::
disk_and_quit() {
    sudo adduser $USER disk
    echo "added you to disk group."
    echo "log out and back in again!"
    exit 1
}
groups | grep -q disk || disk_and_quit

fdisk -l $disk

RAM_MB=2048
NUMCPUS=3

short=$(basename $disk)
name_postfix='_linux'
vm="$short$name_postfix"
vmdk="$HOME/VMs/${short}.vmdk"


echo
echo "----[ review ]----"
echo "disk=$disk"
echo "vm=$vm"
echo "vmdk=$vmdk"
echo "iso=$iso"
echo "----[ OK? (Ctrl-c to exit) ]----"
read _

VBoxManage internalcommands createrawvmdk -filename $vmdk -rawdisk $disk

VBoxManage createvm --name $vm --register

# HDD
VBoxManage storagectl $vm \
    --name sata --add sata --controller IntelAhci --portcount 1
VBoxManage storageattach $vm \
    --storagectl sata --device 0 --port 0 --type hdd --medium $vmdk
# CDROM
VBoxManage storagectl $vm \
    --name ide --add ide --controller PIIX4 --portcount 2
    # yeah, this wants 2 ports. so be it.
VBoxManage storageattach $vm \
    --storagectl ide --device 1 --port 0 --type dvddrive --medium $iso
# Network
VBoxManage modifyvm $vm --nic1 nat
# RAM and CPU cores
VBoxManage modifyvm $vm --memory $RAM_MB
VBoxManage modifyvm $vm --cpus $NUMCPUS

VBoxManage startvm $vm --type gui

