#! /usr/bin/env bash

# Get virtual machine console (using screen).
#
# Note: use Ctrl-a k to exit screen (or Ctrl-a a k if running inside screen).
#
usage="usage: $0 <console-socket>"

trap "{ exit 1; }" ERR
set -o errtrace # Trap in functions.

function info () { echo "$*" 1>&2; }
function error () { info "$*"; exit 1; }

con="$1"

if [ -z "$con" ]; then
  error "missing console socket"
fi

pty="$(dirname "$con")/$(basename -s .sock "$con").pty"

socat "UNIX-CONNECT:$con" "PTY,link=$pty" &
pid="$!"

# Hack around terminal permission issue when running under `su - <user>`.
#
script -q -c "screen $pty" /dev/null

# Note: socat may have already terminated (e.g., VM was shut down).
#
kill "$pid" 2>/dev/null || true
wait