#!/bin/sh

. /usr/local/lib/vmware.sh

get_pipe_file() {
    vmware-vim-cmd vmsvc/device.getdevices $1 | awk '
	/backing = \(vim.vm.device.VirtualSerialPort.PipeBackingInfo\)/ {
	    section = 1;
	}
	section == 1 {
	    if (/},/) {
		if (pipe) {
		    print pipe
		}
		section = 0;
	    } else if (/pipeName = /) {
		pipe = $3;
	    }
	}
	' | sed -n 's/^"\(.*\)",/\1/p'
}

usage() {
    echo "Usage: `basename $0` [-g] <vm>" 1>&2
    exit 1
}

SOCAT="`which socat 2> /dev/null`"

if [ $# -gt 2 ]; then
    usage
elif [ $# -eq 2 ]; then
    case $1 in
	-g)
	    serial=0
	    ;;
	-s)
	    if [ "${SOCAT}" = "" ]; then
		echo "Serial console not avaible, socat is missing" 1>&2
		exit 1
	    fi
	    serial=2
	    ;;
	*)
	    usage
    esac
    vm="$2"
elif [ $# -eq 1 ]; then
    vm="$1"
else
    usage
fi

vmid="`vmid \"${vm}\"`"
if [ "${vmid}" = "" ]; then
    echo "Cannot find virtual machine ${vm}" 1>&2
    exit 1
fi

if [ "${serial}" != "0" -a "${SOCAT}" != "" ]; then
    pipe="`get_pipe_file ${vmid}`"
    if [ "${pipe}" != "" ]; then
	echo ${pipe} | egrep -q "^/"
	if [ $? -ne 0 ]; then
	    vmpath="`abspath ${vmid}`"
	    pipe="`dirname \"${vmpath}\"`/${pipe}"
        fi
        screen ${SOCAT} unix-connect:${pipe} stdio,echo=0,raw
	exit $?
    elif [ "${serial}" = "2" ]; then
	echo "Serial console not available for virtual machine ${vm}" 1>&2
	exit 1
    fi
fi

platform="`uname -i`"
case ${platform} in
    x86_64)
	platform=x64
	;;
    *)
	platform=x86
	;;
esac
xpifile="`find /usr/lib/vmware/webAccess/tomcat/apache-tomcat-*/webapps/ui/plugin/vmware-vmrc-linux-${platform}.xpi`"

tmpdir="`mktemp -d /tmp/vmware-vmrc-${LOGNAME}-XXXXXXXXXX`" && {
    cd ${tmpdir}
    unzip -q ${xpifile}
    vmware-vim-cmd vmsvc/acquiremksticket ${vmid}
    ./plugins/vmware-vmrc -u root -h localhost:8333 -M ${vmid}
    rm -rf ${tmpdir}
}
