#!/bin/bash
#
# $Id: vmware.sh,v 1.4 2009/07/29 20:04:19 root Exp $
#

# List all datastores on server
list_datastores() {
    vmware-vim-cmd hostsvc/storage/fs_info | awk '
        /^[ ]*path = / {
          path = substr($3, 2, length($3)-3)
        }
        /^[ ]*name = / {
          print substr($3, 2, length($3)-3) " " path
        }
    '
}


# Get list of all registered virtual machines.
#
# Returns list in format:
#
#    vmid|displayName|path
#
list_vms() {
    vmware-vim-cmd vmsvc/getallvms | sed -n \
        's/^\([0-9][0-9]*\)[ ]*\([^  ]*\)[ ]*\(\[[^  ]*\] [^  ]*\).*/\1|\2|\3/p'
}


# Convert given path into datastore format.
#
# Eg. dspath /vmfs/volumes/mystore/foo.vmx returns
#     [mystore] foo.vmx
#
dspath() {
    case "$1" in
	/*)
            list_datastores | while read n p ; do
		echo "$1" | egrep -q "^${p}" || continue
		echo -n "[${n}] "
		echo "$1" | cut -c `echo ${p} | wc -m`- | cut -c 2-
		break
	    done
            ;;
	[*)
	    echo "$1"
	    ;;
    esac
}


# Convert given path into filesystem format.
#
# Eg. abspath [mystore] foo.vmx returns
#     /vmfs/volumes/mystore/foo.vmx
#
abspath() {
    case "$1" in
	/*)
            echo "$1"
	    ;;
	[*)
	    ds=`echo "$1" | sed -e 's/^\[\(.*\)\] .*$/\1/'`
	    vmware-vim-cmd hostsvc/datastore/info "${ds}" | \
		sed -n 's/^[ ]*path = \"\(.*\)\",[ ]*/\1/p' | uniq | tr '\n' '/'
	    echo "$1" | sed -e 's/^\[.*\] \(.*\)$/\1/'
	    ;;
	[0-9]*)
	    abspath "`list_vms | sed -n \"s/^$1|.*|\(\[.*\] .*\)$/\1/p\"`"
	    ;;
    esac
}


# Get id for given virtual machine
#
vmid() {
    case "$1" in
	/*)
            ds="`dspath "\${1}\"`"
	    if [ "${ds}" == "" ]; then
		exit
	    fi
            list_vms | awk -F'|' '{print $1 " " $3}' | while read vmid vmpath ; do
		if [ "${vmpath}" = "${ds}" ]; then
		    echo ${vmid}
		    break
		fi
	    done
	    ;;
       [*)
            list_vms | awk -F'|' '{print $1 " " $3}' | while read vmid vmpath ; do
		if [ "${vmpath}" = "${1}" ]; then
		    echo ${vmid}
		    break
		fi
	    done
            ;;
        *)
	    list_vms | awk -F'|' '{print $1 " " $2}' | while read vmid vmname ; do
		if [ "${vmid}" = "${1}" ]; then
		    echo ${vmid}
		    break
		elif [ "${vmname}" = "${1}" ]; then
		    echo ${vmid}
		    break
		fi
	    done
	    ;;
    esac

}
