#!/bin/sh
# vim: set ts=4:
set -e

SCRIPT_NAME="$(basename "$0")"
VERSION='0.12.0'

HELP_MESSAGE="qemu-openrc $VERSION

Connect to a monitor console of a QEMU virtual machine. It's like virsh from
libvirt, but provided directly by QEMU.

Usage:
  $SCRIPT_NAME <VM_NAME | SOCKET_PATH> [command ...]
  $SCRIPT_NAME [-h | --help | -V | --version]

VM_NAME      Name of the QEMU machine to connect (expects QEMU monitor
             socket at /run/qemu/\${VM_NAME}/monitor.sock).
SOCKET_PATH  Path of the QEMU's monitor socket to connect.

Project homepage: <https://github.com/jirutka/qemu-openrc>."

socket_path=''

case "$1" in
	-h | --help)
		echo "$HELP_MESSAGE"
		exit 0
	;;
	-V | --version)
		echo "qemu-openrc $VERSION"
		exit 0
	;;
	/*)
		socket_path="$1"
		break
	;;
	*)
		[ -n "$1" ] || { echo "$HELP_MESSAGE"; exit 1; }
		socket_path="/run/qemu/$1/monitor.sock"
		break
	;;
esac

if [ ! -S "$socket_path" ]; then
	echo "ERROR: QEMU monitor socket $socket_path does not exist!" 1>&2
	exit 2
fi

if [ -n "$2" ]; then
	IFS=$'\n'
	shift
	printf "%b\n" "$*" | socat - "UNIX-CONNECT:$socket_path"
else
	echo 'Connecting to QEMU monitor in interactive mode. Use Ctrl+O to exit.'
	echo 'Note: command "quit" does not exit the monitor, but stops VM!'
	echo ''
	socat -,raw,echo=0,escape=0x0f "UNIX-CONNECT:$socket_path"
fi
printf '\n'
