#!/bin/sh

VMWARECMD="/usr/local/bin/vmware-cmd"
CDHOME="/home/cds"
PREFIX="SLES-10-x86-"

if [ $# -lt 1 ] ; then
    echo "Usage: $0 <vm> <iso>"
    echo "       <vm> is missing"
    exit 1
fi

if [ `$VMWARECMD -l | grep -c $1` -gt 1 ] ; then
    echo "More than one VM matching $1 found:"
    $VMWARECMD -l | grep $1
    exit 1
fi

if [ $# -lt 2 ] ; then
    echo "Usage: $0 <vm> <iso>"
    echo "       <iso> is missing"
    exit 1
fi

cdrom="$2"

if [ ! -e "$cdrom" ] ; then
    if   [ -e "${CDHOME}/${cdrom}" ] ; then
	cdrom="${CDHOME}/${cdrom}"
    elif [ -e "${cdrom}.iso" ] ; then
	cdrom="${cdrom}.iso"
    elif [ -e "${CDHOME}/${cdrom}.iso" ] ; then
	cdrom="${CDHOME}/${cdrom}.iso"
    elif [ -e "${CDHOME}/${PREFIX}${cdrom}" ] ; then
	cdrom="${CDHOME}/${PREFIX}${cdrom}"
    elif [ -e "${CDHOME}/${PREFIX}${cdrom}.iso" ] ; then
	cdrom="${CDHOME}/${PREFIX}${cdrom}.iso"
    else
	echo "File not found: $cdrom"
	exit 1
    fi
fi

vm=`$VMWARECMD -l | grep $1`

if [ -z $vm ] ; then
    echo "Specification of VM must be unique"
    exit 1
fi

if $VMWARECMD $vm getconfig ide1:0.fileName | grep -i -q "$cdrom" ; then
    echo "$vm has $cdrom just set.  Nothing to do."
    exit 0	
fi									

$VMWARECMD $vm disconnectdevice ide1:0
$VMWARECMD $vm setconfig ide1:0.fileName "$cdrom"
$VMWARECMD $vm connectdevice ide1:0

exit 0
