#! /usr/bin/env bash
#
# xephwrap.sh
# Copyright (C) 2018 salt <salt@lap-th-e560-0>
#
# Distributed under terms of the MIT license.
#

name="$(basename $0 .sh)"

function log() {
	[ -z ${1+x} ] && return 1
	printf "\e[94m$name\e[0m: $1\n"
}

function xprompt() {
	[ -z ${1+x} ] && return 2
	[ -z ${2+x} ] || default="$2"; suffix=" [$default]"
	read -p "$1$suffix: "
	if [ "$REPLY" == "" ]; then
		export REPLY="$2"
	fi
}

function validatedep() {
	[ -z ${1+x} ] && return 2
	if ! which "$1" > /dev/null 2>&1; then
		return 1
	fi
	return 0
}

# Validate dependencies
for dep in Xephyr; do
	if ! validatedep "$dep"; then
		log "Failed to validate dependency: \"$dep\""
		exit 1
	fi
done

# Prompt for user interaction
xprompt "Size" "1280x720"
size="$REPLY"

xprompt "Display" "10"
display="$REPLY"

if ! [ "$display" -ge "-1" ]; then
	log "Invalid response for display: \"$display\""
	exit 4
fi
if [ "$display" == "$DISPLAY" ]; then
	log "Response matches host display: \"$display\""
	exit 5
fi

# Start the server up
Xephyr \
	-ac \
	-screen "$size" \
	:"$display" \
	&
disown
log "Started Xephyr server"
exit 0