#!/bin/sh
die() {	printf '%s\n' "$*" >&2; exit 1; }
notfound() { printf '%s not found, sending to the "%s".\n' "$fifo" "$1" >&2; fifo=$serverbase/$1/var/run/socket; }

[ $# -ge 1 ] || die "Syntax: $0 <server version> <command [arguments]>"

server=$1
serverbase=$HOME/servers/$server
fifo=$serverbase/build/var/run/socket
shift

[ -d "$serverbase" ] || die "Server '$server' not found."

[ -e "$fifo" ] || { notfound oldbuild; [ -e "$fifo" ] || notfound revertedbuild; }
[ -p "$fifo" ] || die "$fifo is not a named pipe (fifo).
Is the $server server running?"

printf '%s\n' "$*" > "$fifo"

# hack to start the irc echo for the old instance on a restart
case $server in
restart*)
	irc_echo() {
		sleep 10  # delay for a bit to make sure we get the right log file since log rotation is also delayed
		screen -S wesnoth-mp-servers -X eval 'select lobby-echo' "stuff \"/wl-old $1\012\""
	}
	case $server in
	dev|trunk) ;;
	stable)    irc_echo stable;;
	oldstable) irc_echo oldstable;;
	esac;;
esac
