#!/bin/bash
# xen-console.sh by Stefan Tomanek <stefan.tomanek@wertarbyte.de>
# http://wertarbyte.de/xen-console.shtml

TMPFILE=$(mktemp)
XM="sudo /usr/sbin/xm"

mainMenu() {
    DOMU="$1"

    if ( dialog --output-fd 3 --menu  "Welcome to your XEN control center for the domU '${DOMU}'. $(getStatusMessage $DOMU)" 20 60 8  "status" "Query the status of your domU" "console" "Access the console of your domU"  "create" "Launch your domU"  "shutdown" "Shut down your domU"  "" ""  "password" "Change your password"  "quit" "Exit the XEN control center" 3> $TMPFILE ); then
	SELECTED=$(< $TMPFILE)
	case $SELECTED in
	    status)
		statusDomU $DOMU
	    ;;
	    console)
		attachConsole $DOMU
	    ;;
	    create)
		createDomU $DOMU
	    ;;
	    shutdown)
		shutdownDomU $DOMU
	    ;;
	    password)
		changePassword
	    ;;
	    quit)
		return 1
	    ;;
	esac

	return 0;
    else
	return 1;
    fi
}

getStatus() {
    DOMU="$1"
    $XM list | awk -v DOMU=$DOMU '
	NR > 1 && $1 == DOMU {
	    if ($5 ~ "p") {
		print "FROZEN", $3
	    } else {
		print "UP", $3
	    };
	    FOUND=1
	}
	END {
	    if (!FOUND) {
		print "DOWN";
		exit 1
	    } else {
		exit 0
	    }
	}'
}

getStatusMessage() {
    DOMU="$1"
    < <(getStatus $DOMU) read STATE MEM
    MESSAGE="Your domain is currently $STATE"
    if [ "$STATE" != "DOWN" ]; then
	MESSAGE="$MESSAGE and has $MEM MiB of memory assigned"
    fi
    MESSAGE="$MESSAGE."
    echo $MESSAGE
}

statusDomU() {
    DOMU="$1"
    dialog --msgbox "$(getStatusMessage $DOMU)" 10 40
}

attachConsole() {
    DOMU="$1"
    dialog --msgbox "You can exit the console by pressing ALT-]" 10 40
    $XM console $DOMU
}

shutdownDomU() {
    DOMU="$1"
    if dialog --defaultno --yesno "Are you sure about shutting down '${DOMU}'? There will be no additional warning." 10 40; then
	$XM shutdown $DOMU
    fi
}

createDomU() {
    DOMU="$1"
    if dialog --defaultno --yesno "Are you sure about starting the new domU '${DOMU}'?" 10 40; then
	$XM create ${DOMU}.cfg
    fi
}

changePassword() {
    passwd
}

MYSELF=$(basename $0 .sh)
DOMU=${MYSELF##xc-}
while mainMenu $DOMU; do
    true;
done
rm $TMPFILE

