#!/bin/bash
# Version 3

# Lists available 7dtd instances.
# Returns:
#  0

. /usr/local/bin/7dtd-common.sh
checkRootLoadConf

listInstances() {
	printf "%-*s | %-*s | %-*s | %-*s\n" 20 "Instance name" 8 "Running" 7 "Players" 5 "Port"
	printf -v line "%*s-+-%*s-+-%*s-+-%*s\n" 20 " " 8 " " 7 " " 5 " "
	echo ${line// /-}
	for I in $(getInstanceList); do
		if [ $(isRunning $I) -eq 1 ]; then
			run="yes"
			tel=$(telnetCommand $I lp)
			cur=`echo $tel | sed "s/\r/\n/g" | sed "s/^ //g" | grep "Total of " | cut -d\  -f 3`
		else
			run="no"
			cur="-"
		fi

		max=$(getConfigValue $I ServerMaxPlayerCount)
		port=$(getConfigValue $I ServerPort)

		printf "%-*s | %*s |   %2s/%2d | %5d\n" 20 "$I" 8 "$run" $cur $max $port
	done
	exit 0
}

showInfo() {
	checkInstanceValid $1

	line() {
		printf "    %-*s %s\n" 15 "$1" "$2"
	}
	
	echo

	echo "7dtd instance: $1"
	echo

	if [ $(isRunning $1) -eq 1 ]; then
		echo "Status: Running"
		echo "Open ports:"
		netstat -nlp | grep $(getInstancePID $1) | sed -r 's/^([^ ]*)\s+.*[^ :]*:([^ ]*).*[^ :]*:[^ ]*.*/    \2 (\1)/g' | sort
		tel=$(telnetCommand $1 lp)
		cur=`echo $tel | sed "s/\r/\n/g" | sed "s/^ //g" | grep "Total of " | cut -d\  -f 3`
		echo "Players: $cur"
	else
		echo "Status: NOT running"
	fi

	echo
	echo "Game info:"
	line "Server name:" $(getConfigValue $1 ServerName)
	line "Password:" $(getConfigValue $1 ServerPassword)
	line "Max players:" $(getConfigValue $1 ServerMaxPlayerCount)
	line "World:" $(getConfigValue $1 GameWorld)

	echo
	echo "Network info:"
	line "Port:" $(getConfigValue $1 ServerPort)
	line "Public:" $(getConfigValue $1 ServerIsPublic)
	if [ "$(getConfigValue $1 ControlPanelEnabled)" = "false" ]; then
		cp="off"
	else
		cp="Port $(getConfigValue $1 ControlPanelPort), Pass $(getConfigValue $1 ControlPanelPassword)"
	fi
	line "Control Panel:" "$cp"
	if [ "$(getConfigValue $1 TelnetEnabled)" = "false" ]; then
		tn="off"
	else
		tn="Port $(getConfigValue $1 TelnetPort), Pass $(getConfigValue $1 TelnetPassword)"
	fi
	line "Telnet:" "$tn"

	echo
	exit 0
}

showHelp() {
	name=`basename $0`
	echo "Unknown parameter: $1"
	echo "Usage:"
	echo "  $name [list]          - List all instances"
	echo "  $name show <instance> - Show detailed info on the given instance"
	exit 0
}

COMMAND=${1:-list}

case "$COMMAND" in
	list)
		listInstances
	;;
	show)
		showInfo $2
	;;
	*)
		showHelp $COMMAND
esac
exit 1
