#!/bin/bash
#
WD=/tmp/hpinit-$$

if [ $# -eq 2 ]; then
    VMNAME=`basename "$1" -s ".ova"`
    vboxmanage unregistervm $VMNAME --delete &>/dev/null
    vboxmanage import --vsys 0 --vmname $VMNAME --memory 4096 --cpus 2 $1
    vboxmanage modifyvm $VMNAME --nic1 hostonly --hostonlyadapter1 vboxnet0 --macaddress1 $2
else
    echo "Usage: $0 <hp_image> <MAC address>
fi

if [ -z "`which VBoxManage`" ]; then
    echo "'VBoxManage' command has not found. Probably VirtualBox is not installed."
    exit 1
fi
if [ -z "`which genisoimage`" ]; then
    echo "'genisoimage' command has not found. Please, install it."
    exit 1
fi

rm -rf $WD
mkdir $WD
cd ~/.ssh
if [ ! -r ~/.ssh/id_rsa ]; then
    ssh-keygen -b 2048 -t rsa -f "id_rsa" -q -N ""
fi
cd $WD
head -c -1 >user-data <<EOF
#cloud-config
users:
  - name: root
    ssh_pwauth: False
    ssh_authorized_keys:
      - 
EOF
cat ~/.ssh/id_rsa.pub >>user-data
touch meta-data
genisoimage  -output seed.iso -volid cidata -joliet -rock -input-charset utf-8 -quiet user-data meta-data
rm -f user-data
rm -f meta-data
VBoxManage storageattach $VMNAME --storagectl SATA --port 1 --device 0 --type dvddrive --hotpluggable on --medium $WD/seed.iso
VBoxManage startvm $VMNAME --type headless