#!/usr/bin/env bash

if [ $# != 3 ]; then
	echo "Usage: $0 </dev/diskX> <vmdk-file> <virtual-machine>"
	echo -e "\tATTENTION: This script will grant every user on the machine full access to the SDCARD!!!"
	echo -e "\tThe script will run certain commands with sudo. Make sure you have the permission to run these commands."
	echo -e "\tMake sure that you run this script as the user who owns the virtual machines.\n\n"
	echo -e "\t</dev/diskX> - device node of the SD card. You can retrieve this information by running \"diskutil list\""
	echo -e "\t<vmdk-file> - the script will create a vmdk-file, which maps to the device node."
	echo -e "\t<virtual-machine> - reference to the virtual machine that will receive the disk. This can be either the name or the UUID of the machine."
	exit 1
fi

dev_node=$1
vmdk_file=$2
vm=$3

# check if the first parameter points to a filename that looks like a
# disk device node
if  [[ $dev_node != /dev/disk? ]] ; then
	echo "ERROR: Device $dev_node does not start with /dev/disk, but it should."
	exit 1
fi

if [ -e $vmdk_file ]; then
	echo "ERROR: VMDK file should not yet exist!"
	exit 1;
fi

echo "Unmounting SD card from system ..."
sudo diskutil unmountDisk $dev_node
if [ $? != 0 ]; then
	echo "ERROR: Could not unmount disk $dev_node. Cannot proceed!"
	exit 1
fi


echo "Creating VMDK file that maps to disk $dev_node"
sudo VBoxManage internalcommands createrawvmdk -filename $vmdk_file -rawdisk $dev_node
if [ $? != 0 ]; then
	echo "ERROR: Could not create VMDK file $vmdk_file. Cannot proceed!"
	exit 1
fi

echo "Setting permissions to disk ..."
sudo chmod 666 $dev_node
if [ $? != 0 ]; then 
	echo "ERROR: Could not set device node permissions. Cannot proceed!"
	exit 1
fi

echo "Setting permissions to file node ..."
sudo chmod 666 $vmdk_file
if [ $? != 0 ]; then 
	echo "ERROR: Could not set vdmk file permissions. Cannot proceed!"
	exit 1
fi


echo "Extracting first SATA port ..."
port=`VBoxManage showvminfo "$vm"  | grep '^SATA' | tail -1 | awk '{print $2}' | sed -e 's/(//;s/,//'`
if [ $? != 0 ]; then
	echo "ERROR: Could not find SATA port. You need to manually attach $vmdk_file to the VM."
	exit 1
fi

# take next port
let "port+=1"

echo "Attaching VMDK file to virtual machine ..."
VBoxManage storageattach "$vm" --medium $vmdk_file --storagectl SATA --port $port --type hdd
if [ $? != 0 ]; then
	echo "ERROR: Could not attach VMDK file to VM. You need to do this manually."
	exit 1
fi

echo "Done!"

echo "You can now start the virtual machine. Please make sure that any partitions on the disk are unmounted when the machine is started. Otherwise you will get an error message."
