#!/bin/sh /etc/rc.common
################################################################################
#                                                                              #
# Polish Koders Team 2010                                                      #
#                                                                              #
# contact: http://pkteam.pl                                                    #
#                                                                              #
################################################################################
#
# Card Server general init script
# version $Revision: 300 $ $Date: 2010-12-31 21:05:58 +0100 (pią) $
#

START=35

EXTRA_COMMANDS="status config"
EXTRA_HELP=$(echo -e "	config	< |phoenix|internal|both> Set new Card Server config\n \
	status	Show current Card Server status")

CONF_EMUMAN="config.plugins.emuman"

CONF_DIR="/var/keys"

FLAVOR=$(config_get "${CONF_EMUMAN}.cs")
CS="newcs"


# Prepare cs configuration arguments 
#
prepare_conf() { #flavor
	case "$1" in
	  phoenix)	CONF="-C ${CONF_DIR}/newcs_phoenix.xml";;
	  internal)	CONF="-C ${CONF_DIR}/newcs_internal.xml";;
	  both)		CONF="-C ${CONF_DIR}/newcs_both.xml";;
	  *)		help
	  		exit 1;;
	esac
	echo "${CONF}"
}

# Prepare cs enviroment variables
#
prepare_env() {
	CMDENV="PATH=/var/cardserver "
	echo "${CMDENV}"
}

start() {
	if [ -z "${FLAVOR}" ]; then
	  echo "Card Server not configured"
	  return
	fi

	local pids=$(pidof ${CS})
	if [ ! -z "${pids}" ]; then
	  echo "${CS} alredy running with pids: [${pids}]"
	  return
	fi
	
	echo "Starting ${CS}"
	echo "Starting ${CS}" > /dev/dbox/vfd
	eval "$(prepare_env)$CS $(prepare_conf $FLAVOR) > /dev/null"
}

stop() {
	if [ -z "${CS}" ]; then
	  echo "Card Server not configured"
	  return
	fi
	echo "Stopping ${CS}"
	killall -15 "${CS}" 2> /dev/null
}

status() {
	if [ -z "${CS}" ]; then
	  echo "Card Server not configured"
	  return
	fi

	local pids=$(pidof ${CS})
	if [ -z "${pids}" ]; then
	  echo "Not running ${CS}"
	else
	  echo "Running ${CS}: [${pids}]"
	fi
}

config() {
	if [ -z "$1" ]; then
	  config_set "${CONF_EMUMAN}.cs" ""
	  echo "Card Server disabled"
	  return
	fi
	config_set "${CONF_EMUMAN}.cs" "$1"
	echo "Card Server ${CS} $1 configured"
}
