#!/bin/bash

function find_util() {
	local util=$1
	for dir in /bin /usr/bin /sbin /usr/sbin; do
		[ ! -x $dir/$util ] && continue
		echo $dir/$util
		return
	done
	# Last chance: it's in PATH
	echo $util
}

function syslogger() {
	[ ! -x $LOGGER ] && return
	$LOGGER -t "VZTOOLS_udev" $*
}

function cleanup() {
	if [ $1 -eq 0 -a -x $EJECT ]; then
		$EJECT $DEVNAME > /dev/null 2>&1
		[ $? -ne 0 ] && syslogger "Failed to eject $DEVNAME"
	else
		# For debugging
		umount $DEVNAME > /dev/null 2>&1
		[ $? -ne 0 ] && syslogger "Failed to umount $DEVNAME"
	fi
	rm -rf $DIR > /dev/null 2>&1
	exit $1
}

function error() {
	echo $*
	syslogger $*
	cleanup 1
}

DIR=`mktemp -d /tmp/toolsXXX`
LOGGER=`find_util logger`
EJECT=`find_util eject`
BLKID=`find_util blkid`
TOOLS_INSTALLER="install"
LABEL="vz-tools-lin"

# Check that started manually or from udev
if [ "x$DEVNAME" = "x" ]; then
	DEVNAME=`$BLKID -l -o device -t LABEL=$LABEL 2>/dev/null | grep -E -m 1 ".*"`
	[ "x$DEVNAME" = "x" ] && error "Can't find ISO with label $LABEL"
else
	# Check that udev failed
	[ "x$ID_FS_LABEL" != "x$LABEL" ] && error "Incorrect tools ISO"
fi

mount $DEVNAME $DIR > /dev/null 2>&1 || error "Failed to mount $DEVNAME $LABEL disk"

[ ! -x $DIR/$TOOLS_INSTALLER ] && error "Incorrect tools ISO"

$DIR/$TOOLS_INSTALLER 2>&1 | syslogger
test ${PIPESTATUS[0]} -eq 0 || error "Failed to install tools"

syslogger "Virtuozzo guest tools successfully installed"

cleanup 0
