#!/usr/bin/env bash

SOCKET=$1
PROTOCOL=unix-connect

function is_console() {
	[[ $(basename $SOCKET) =~ .*serial.* ]]
}

function serial_cleanup() {
  # if this is a serial connection, see if there is a previous
  # connection that must be cleaned up before starting a new one.
  if is_console; then
    pgrep socat | while read pid; do
      tr '\0' '\n' < "/proc/$pid/cmdline" \
      | grep -qE "^$PROTOCOL:/$SOCKET$" || continue
      kill "$pid"
    done
  fi
}

# only one serial connection can exist at a time.
serial_cleanup

if ! [ -S "$SOCKET" ]; then
	echo "Virtual Machine's $SOCKET socket is currently unavailable"
	exit 1
fi

# define defaults for both ends of the connection

TO_VIRTUAL_MACHINE="$PROTOCOL:/$SOCKET"
FROM_CLIENT="stdio"

if is_console; then
  # enable raw mode for console access
  stty -echo
  FROM_CLIENT="stdio,cfmakeraw"
fi

exec socat "$TO_VIRTUAL_MACHINE" "$FROM_CLIENT"
