#!/bin/ksh
#
# Component: dicom
#
# Description:
#  Control script of component dicom
#

#--- INIT ------------------------------
#needs $HOME
. $HOME/etc/ctrl.main.shi

[ -f $HOME/etc/setenv.sh ] && . $HOME/etc/setenv.sh


#--- FUNC ------------------------------
do_shell_()
{
	if [ -f "$ETC/virthost.sh" ]; then
		. "$ETC/virthost.sh"
	fi
	[ -z "$DICOM_PORT" ] && DICOM_PORT=104
	[ -z "$DICOM_TLS_PORT" ] && DICOM_TLS_PORT=2762

	cat <<-EndOfInlineData
		DICOM_HOME=$HOME/component/dicom
		DICOM_VAR=\${SHARED_VAR}/dicom
		DICOM_SERVERIP=$BINDIP
		DICOM_PORT=$DICOM_PORT
		DICOM_TLS_PORT=$DICOM_TLS_PORT
		DICOM_AE_TITLE="PBUILDER"
		DICOM_PID=$RUN/pb-scp.pid
		MPPSTBL=MPPS
	EndOfInlineData
} #do_shell_()


do_crontab_()
{
	# Get time for starting getorders.sh from crontabSchedule settings
	[ -f "$CONF/crontabSchedule.shi" ] && . $CONF/crontabSchedule.shi
	
	if has_role_ "application" ; then
	
		[ -z "$GetOrders" ] && GetOrders="18,48 *"
	
		cat <<-EOI
			$GetOrders * * * $DICOM_HOME/bin/getorders.sh >/dev/null 2>&1
		EOI
	fi
} #do_crontab_()


#
# Checks if var/dicom exists and is linked to shared/var/dicom
# at non-application farm servers.
# Creates the var/dicom link if does not yet exist
#
check_var_dicom_()
{
	local LinkEnd

	if [ -L "${VAR}/dicom" ] ; then
		LinkEnd=$( readlink "${VAR}/dicom" )
		if [ "${LinkEnd}" = "${SHARED_VAR}/dicom" ] ; then
			if [ ! -d "${SHARED_VAR}/dicom" ] ; then
				# shared/var/dicom does not yet exist
				echo "Warning: ${SHARED_VAR}/dicom directory does not yet exist." >&2
				return 0
			fi
		else
			echo "Error: ${VAR}/dicom points to an unexpected location: ${LinkEnd}" >&2
			return 1
		fi
	elif [ -e "${VAR}/dicom" ] ; then
		# shared/var/dicom also exists - conflict
		echo "[Alert] ${VAR}/dicom is not a link." >&2
		echo "[Alert]         Needs to be resolved manually" >&2
	fi

	return 0
}



#
# Checks and creates var/dicom and shared/var/dicom
# on application and single servers
#
check_and_create_var_dicom_()
{
	local LinkEnd
	
	if [ ! -L "${VAR}/dicom" ] ; then
		# var/dicom is not a link
		if [ ! -e "${VAR}/dicom" ] ; then
			# var/dicom does not exist
			if [ ! -d "${SHARED_VAR}/dicom" ] ; then
				echo "Creating ${SHARED_VAR}/dicom"
				mkdir "${SHARED_VAR}/dicom" || return 1
			fi
			ln -sfT "${SHARED_VAR}/dicom" "${VAR}/dicom" || return 1
			return 0
		elif [ -d "${VAR}/dicom" ] ; then
			# var/dicom is a directory (legacy)
			if [ -L "${SHARED_VAR}/dicom" ] ; then
				# shared/var/dicom is a link
				LinkEnd=$( readlink "${SHARED_VAR}/dicom" )
				if [ "${LinkEnd}" = "${VAR}/dicom" ] ; then
					echo "[Alert] ${VAR}/dicom is still a directory (vs a link to ${SHARED_VAR}/dicom)." >&2
					echo "[Alert]         Needs to be resolved manually" >&2
					return 0
				else
					echo "Error: ${SHARED_VAR}/dicom points to an unexpected location: ${LinkEnd}" >&2
					return 1
				fi
			elif [ -d "${SHARED_VAR}/dicom" ] ; then
				# shared/var/dicom also exists - conflict
				echo "[Alert] Both ${VAR}/dicom and ${SHARED_VAR}/dicom are directories." >&2
				echo "[Alert]         Needs to be resolved manually" >&2
				return 0
			elif is_single_server_ ; then
				# No shared/var/dicom yet at a single server
				echo "Moving legacy ${VAR}/dicom to ${SHARED_VAR}/dicom"
				mv "${VAR}/dicom" "${SHARED_VAR}/dicom" || return 1
				ln -sfT "${SHARED_VAR}/dicom" "${VAR}/dicom" || return 1
				return 0
			else
				# No shared/var/dicom yet at the app server
				echo "[Alert] ${VAR}/dicom is a directory and ${SHARED_VAR}/dicom does not exist" >&2
				echo "[Alert]         Linking ${SHARED_VAR}/dicom to ${VAR}/dicom" >&2
				echo "[Alert]         Needs to be resolved manually" >&2
				ln -sfT "${VAR}/dicom" "${SHARED_VAR}/dicom" || return 1
				return 0
			fi
		else
			echo "Error: ${VAR}/dicom exists but neither link nor directory" >&2
			return 1
		fi
	else
		LinkEnd=$( readlink "${VAR}/dicom" )
		if [ "${LinkEnd}" = "${SHARED_VAR}/dicom" ] ; then
			if [ ! -d "${SHARED_VAR}/dicom" ] ; then
				# shared/var/dicom does not yet exist
				echo "Warning: creating missing ${SHARED_VAR}/dicom directory." >&2
				mkdir "${SHARED_VAR}/dicom" || return 1
				return 0
			fi
		else
			echo "Error: ${VAR}/dicom points to an unexpected location: ${LinkEnd}" >&2
			return 1
		fi
	fi
}


#
# Creates an initial pbscp.cfg for new installs
# Does nothing if the file already exists
#
# $1 - path to the pbscp.cfg file to create
#
check_and_create_pbscp_config_()
{
	OutputFile="$1"
	[ -f "${OutputFile}" ] && return

	# Default Transfer Syntax = SCU Defined
	# Originally ts.cfg contained 't[i|e|b]'
	# we need to change them to 'x[i|e|b]'
	# Factory Default is Little Endian Preferred (xe)

	cat<<-EOFPBSCPCFG >"${OutputFile}"
		AE_TITLE="${DICOM_AE_TITLE}"
		PORT="${DICOM_PORT}"
		TLS_PORT="${DICOM_TLS_PORT}"
		TRANSFER_SYNTAX="xe"
		PDU_SIZE="65536"
		MAX_ASSOCIATIONS="16"
		CASE_INSENSITIVE="true"
		EMPTY_MATCHING="false"
		PROMISCUOUS_MODE="true"
		STORESCU_FLAG="-R"
	EOFPBSCPCFG
}

#
# Creates an initial qr.cfg file for new installs
# Does nothing if the file already exists
#
# $1 - path to the qr.cfg file to create
#
create_initial_qr_config_()
{
	local OutputFile="$1"
	[ -f "${OutputFile}" ] && return

	cat<<-EOFQRCFG >"${OutputFile}"
		NetworkTCPPort = ${DICOM_PORT}
		NetworkTLSPort = ${DICOM_TLS_PORT}
		MaxPDUSize = 65536
		MaxAssociations = 16
		ReceiveTimeout = 30
		SendTimeout = 30
		ConnectionTimeout = 30
		EmptyMatching = false
		CaseInsensitive = true
		TransferSyntax = xe
		PromiscuousServices = 00000003

		HostTable BEGIN
		_-_LOOPBACK_-_ = (${DICOM_AE_TITLE}, ${SERVERIP}, ${DICOM_PORT}, TCP, 30, 30, 30, 000003f7, false, true, xe )
		_-_ALLOWED_-_ = _-_LOOPBACK_-_
		HostTable END

		AETable BEGIN
		${DICOM_AE_TITLE} /home/medsrv/tmp RW (0,0mb) ANY
		AETable END
	EOFQRCFG
}


#
# Check and create qr.cfg link for regular start
#
link_qr_cfg_()
{
	local LinkEnd

	if [ ! -f "${DICOM_VAR}/qr.cfg.gui" ] ; then
		# No GUI generated qr.cfg
		if [ -f "${DICOM_VAR}/qr.cfg" ] ; then
			if [ -L "${DICOM_VAR}/qr.cfg" ] ; then
				echo "Warning: ${DICOM_VAR}/qr.cfg is a symbolic linc to $(readlink "${DICOM_VAR}/qr.cfg")"
				return 0
			else
				echo "Moving legacy ${DICOM_VAR}/qr.cfg to ${DICOM_VAR}/qr.cfg.gui"
				mv "${DICOM_VAR}/qr.cfg" "${DICOM_VAR}/qr.cfg.gui" || return 1
			fi
		else
			echo "Creating initial ${DICOM_VAR}/qr.cfg.gui"
			create_initial_qr_config_ "${DICOM_VAR}/qr.cfg.gui"
		fi
		chmod a+r "${DICOM_VAR}/qr.cfg.gui"
		ln -sfT "${DICOM_VAR}/qr.cfg.gui" "${DICOM_VAR}/qr.cfg" || return 1
		return 0
	fi

	# java creates qr.cfg.ui without 'other readable' permission
	chmod a+r "${DICOM_VAR}/qr.cfg.gui"

	# There is a GUI generated qr.cfg
	if [ -L "${DICOM_VAR}/qr.cfg" ] ; then
		# a link exists, but we will relink 
		# (-f follows links, so we had to check this first)
		:
	elif [ -f "${DICOM_VAR}/qr.cfg" ] ; then
		# Replace GUI cfg with legacy qr.cfg
		echo "Moving legacy ${DICOM_VAR}/qr.cfg to ${DICOM_VAR}/qr.cfg.gui"
		mv "${DICOM_VAR}/qr.cfg" "${DICOM_VAR}/qr.cfg.gui" || return 1
	fi

	# link qr.cfg to the GUI cfg
	ln -sfT "${DICOM_VAR}/qr.cfg.gui" "${DICOM_VAR}/qr.cfg" || return 1
	return 0
}


#
# Creates a qr.cfg for starting in service mode
# Allows connections only from Parent and Child servers
#
# $1 - path to the service qr.cfg file to create
#
check_and_create_service_qr_config_()
{
	local OutputFile="$1"

	local AE_TITLE PORT TLS_PORT TRANSFER_SYNTAX PDU_SIZE
	local MAX_ASSOCIATIONS PROMISCUOUS_MODE
	local PROMISCUOUS_SERVICES CASE_INSENSITIVE EMPTY_MATCHING
	local RECEIVE_TIMEOUT SEND_TIMEOUT ALTERNATIVE_AE_TITLES

	local ProcessMode
	local GenRes
	local Query
	local HostTable TmpHostTable AuthorizedHosts AltAETitle


	. "${DICOM_VAR}/pb-scp.cfg"

	PROMISCUOUS_MODE="false"

	Query="select ID,HOSTNAME,AE,PORT,PROTOCOL,SERVICE from ${TARGETTBL}, ${DEVSERVTBL} where TYPE='C' or TYPE='P' and ID=DEVICE order by ID;"
	TmpHostTable=$( ${TOOLS_HOME}/sql.sh "${Query}" -N 2>/dev/null )

	GenRes=$?

	if [ $GenRes -ne 0 ] ; then
		echo "Error: $DICOM_VAR/qr.cfg could not be created" >&2
		return 1
	fi

	HostTable=$( echo "${TmpHostTable}" | \
		sed 's/[ ,(=)]/_/g' | \
		$DICOM_HOME/mkhosttable.awk -vFS='\t' -vip="${SERVERIP}" \
			-vport="${PORT:-${DICOM_PORT}}" -vdae="${DICOM_AE_TITLE}" -vae="${AE_TITLE:-${DICOM_AE_TITLE}}" )

	AuthorizedHosts="ANY"
	[ "{$PROMISCUOUS_MODE}" = "false" -a "$GenRes" -eq 0 ] && AuthorizedHosts="_-_ALLOWED_-_"

	cat >"${OutputFile}" <<-ENDOfHostTable
		NetworkTCPPort = ${PORT:-${DICOM_PORT}}
		NetworkTLSPort = ${TLS_PORT:-${DICOM_TLS_PORT}}
		MaxPDUSize = ${PDU_SIZE:-65536}
		MaxAssociations = ${MAX_ASSOCIATIONS:-16}
		ReceiveTimeout = ${RECEIVE_TIMEOUT:-30}
		SendTimeout = ${SEND_TIMEOUT:-30}
		ConnectionTimeout = ${CONNECTION_TIMEOUT:-30}
		EmptyMatching = ${EMPTY_MATCHING:-false}
		CaseInsensitive = ${CASE_INSENSITIVE:-true}
		TransferSyntax = ${TRANSFER_SYNTAX:-xd}
		PromiscuousServices = ${PROMISCUOUS_SERVICES:-00000003}

		${HostTable}

		AETable BEGIN
		${AE_TITLE:-${DICOM_AE_TITLE}} $TMP RW (0,0mb) ${AuthorizedHosts}
	ENDOfHostTable

	# ksh can't resolve new lines within variables in a 'here document' block :(
	if [ -n "${ALTERNATIVE_AE_TITLES}" ] ; then
		for AltAETitle in ${ALTERNATIVE_AE_TITLES} ; do
			echo "${AltAETitle} ${TMP} RW (0,0mb) ${AuthorizedHosts}" >>"${OutputFile}"
		done
	fi

	if [ -n "${ARCHIVE_AETITLE}" ] ; then
		echo "${ARCHIVE_AETITLE} ARCHIVE RW (0,0mb) ${AuthorizedHosts}" >>"${OutputFile}"
	fi

	echo "AETable END" >>"${OutputFile}"
}


#
# Creates a custom qr.cfg file for starting dicom component in service mode and
# relinks qr.cfg to point to this custom qr.cfg
#
link_service_qr_cfg_()
{
	check_and_create_service_qr_config_ "${DICOM_VAR}/qr.cfg.service" || return 1
	ln -sfT "${DICOM_VAR}/qr.cfg.service" "${DICOM_VAR}/qr.cfg" || return 1
	return 0
}


#
# Initializes the dicom component at all servers.
#
# - At all servers
#      - creates shared/var/dicom
#      - moves legacy data from the var/dicom to shared/var/dicom
#  - on applic
#  - creates initial pbscp.cfg and qr.cfg.gui for new installs
#  - links qr.cfg according to regular or service mode
#
# $1 - start mode
#
do_initalways_()
{
	local StartMode="$1"

	if has_role_ "application" ; then
		check_and_create_var_dicom_ || return 1

		check_and_create_pbscp_config_ "${DICOM_VAR}/pb-scp.cfg"

		# Check and create mappings directory
		[ ! -d "$DICOM_VAR/mappings" ] && mkdir "$DICOM_VAR/mappings"

		# Check and create devices directory
		[ ! -d "$DICOM_VAR/devices" ] && mkdir "$DICOM_VAR/devices"

		if [ "${StartMode}" = "service" ] ; then
			link_service_qr_cfg_
		else
			link_qr_cfg_
			# delete qr.cfg.service if exists
			[ -f "${DICOM_VAR}/qr.cfg.service" ] && rm "${DICOM_VAR}/qr.cfg.service"
		fi
	else
		check_var_dicom_ || return 1
	fi

	return 0
}


do_start_()
{
	if ! any_role_wants_ "dicom" ; then
		echo "Error: Component dicom is disabled at this server" >&2
		return 1
	fi


	if [ ! -f "${DICOM_VAR}/qr.cfg" ] ; then
		echo "Error: ${DICOM_VAR}/qr.cfg does not exist" >&2
		return 1
	fi

	# java creates qr.cfg.ui without 'other readable' permission
	[ -f "${DICOM_VAR}/qr.cfg.gui" ] && chmod a+r "${DICOM_VAR}/qr.cfg.gui"

	. "${DICOM_VAR}/pb-scp.cfg"

	PB_SCP_OPT="+${TRANSFER_SYNTAX:-xd}"

	# TLS options
	TLS_KEY_FILE="$OPENSSL_PRIVKEY"
	TLS_CERT_FILE="$OPENSSL_CERT_DEFAULT"
	PB_SCP_OPT="$PB_SCP_OPT +tls $TLS_KEY_FILE $TLS_CERT_FILE -ic +ps -dhl"

	# asroot needs PB_SCP_OPT, pb-scp needs CASE_INSENSITIVE
	export PB_SCP_OPT CASE_INSENSITIVE EMPTY_MATCHING

	if [ -f "$CONF/charset.cfg" ] ; then
		# Character set settings - set environment variables
		. "$CONF/charset.cfg"

		export PB_CHARSET PB_DCM_CHARSET
	fi

	if [ "$1" = "debug" ] ; then
		cat <<-ENDDICOMOPTION > $RUN/dicom.options
			DICOM_OPTIONS="-v -d"
		ENDDICOMOPTION
	elif [ "$1" = "nodebug" ] ; then
		[ -f "$RUN/dicom.options" ] && rm $RUN/dicom.options
	fi

	$ASROOT dicom.asr start

} #do_start_()


do_stop_()
{
	$ASROOT dicom.asr stop

} #do_stop_()


#
# Counts the child processes of pb-scp
#
# $1 - the process ID of the root pb-scp process
#
# output: the count of the child processes
#
count_child_processes_() {
	local procId="$1"

	ps -o pid= --ppid "${procId}" | wc -l
}


#
# Checks if the count of the child processes is above the 'full' threshold.
#
# To be called only when the C-Echo fails. Receives the process count before the C-Echo in a parameter,
# but also gets the current process count. Both process counts will be checked.
#
# Exits with a warning when either process count reaches the threshold.
#
# $1 - the process ID of the root pb-scp process
# $2 - the threshold
# $3 - the process count (before the echo)
#
check_threshold_() {
	local procId="$1"
	local threshold="$2"
	local procCount="$3"

	# process count before echo
	if [ ${procCount} -ge ${threshold} ] ; then
		/usr/bin/logger -p $LOG_FACILITY.error -t "dicom-ctrl[$$]" "pb-scp echo failed, but current association count (${procCount}) reached threshold (${threshold})"
		echo "WARNING"
		exit
	fi

	# process count after echo
	procCount=$( count_child_processes_ "${procId}" )
	if [ ${procCount} -ge ${threshold} ] ; then
		/usr/bin/logger -p $LOG_FACILITY.error -t "dicom-ctrl[$$]" "pb-scp echo failed, but current association count (${procCount}) reached threshold (${threshold})"
		echo "WARNING"
		exit
	fi
}


do_status_()
{
	local pbscpPid;
	local procName;
	local MAX_ASSOCIATIONS;
	local assocThreshold;
	local countAssoc;

	if [ ! -f $DICOM_PID ]; then
		echo "STOPPED"
		exit
	fi

	pbscpPid=$( cat "$DICOM_PID" )
	procName=$( ps -o comm= --pid ${pbscpPid} )

	if [ "pb-scp" != "${procName}" ] ; then
		/usr/bin/logger -p $LOG_FACILITY.error -t "dicom-ctrl[$$]" "${pbscpPid} does not exist or is not a pb-scp process ('${procName}')"
		echo "ERROR"
		exit
	fi

	. $DICOM_VAR/pb-scp.cfg

	[ -z "$AE_TITLE" ] && AE_TITLE="$DICOM_AE_TITLE"
	[ -z "$PORT" ] && PORT="$DICOM_PORT"
	[ -z "$TLS_PORT" ] && TLS_PORT="$DICOM_TLS_PORT"
	[ -z "${MAX_ASSOCIATIONS}" ] && MAX_ASSOCIATIONS=16

	# 90%
	assocThreshold=$(( ${MAX_ASSOCIATIONS} * 9 / 10 ))
	countAssoc=$( count_child_processes_ "${pbscpPid}" )
	if [ ${countAssoc} -ge ${MAX_ASSOCIATIONS} ] ; then
		/usr/bin/logger -p $LOG_FACILITY.error -t "dicom-ctrl[$$]" "pb-scp hit max associations (${MAX_ASSOCIATIONS})"
		echo "WARNING"
		exit
	fi

	# Checking transparent TCP connection
	$DCMTK_HOME/bin/echoscu --call $AE_TITLE -aet $AE_TITLE $SERVERIP $PORT >/dev/null 2>&1
	if [ $? -ne 0 ]; then
		check_threshold_ "${pbscpPid}" "${assocThreshold}" "${countAssoc}"
		/usr/bin/logger -p $LOG_FACILITY.error -t "dicom-ctrl[$$]" "DICOM C-Echo failed (TCP)"
		echo "ERROR"
		exit
	fi

	# Checking TLS TCP connection
	TLS_KEY_FILE="$OPENSSL_PRIVKEY"
	TLS_CERT_FILE="$OPENSSL_CERT_DEFAULT"
	TLS_OPT="+tls $TLS_KEY_FILE $TLS_CERT_FILE -ic +ps"

	$OPENSSL_PASS | $DCMTK_HOME/bin/echoscu --call $AE_TITLE -aet $AE_TITLE $TLS_OPT $SERVERIP $TLS_PORT >/dev/null 2>&1
	if [ $? -ne 0 ]; then
		check_threshold_ "${pbscpPid}" "${assocThreshold}" "${countAssoc}"
		/usr/bin/logger -p $LOG_FACILITY.error -t "dicom-ctrl[$$]" "DICOM C-Echo failed (TLS)"
		echo "ERROR"
		exit
	fi

	echo "OK"
	exit

} #do_status_()

do_beforesubmit_()
{
	do_stop_

} #do_beforesubmit_()

do_aftersubmit_()
{
	do_start_

} #do_aftersubmit_()

do_emergency_()
{
	do_stop_
	do_start_

} #do_emergency_()


do_monitor_()
{
	# checking number of pb-scp processes
	numProc=$(ps -C pb-scp h -o "%u" | grep "\<$USER\>" | wc -l)
	MAX_ASSOCIATIONS="16"
	[ -f "$DICOM_VAR/pb-scp.cfg" ] && . "$DICOM_VAR/pb-scp.cfg"

	echo "$numProc ${MAX_ASSOCIATIONS}" | awk '{printf("dicom_proc=%1.2f\n", $1 * 100 / $2);}'
}

#
# List files/tables to be backed up grouped by categories
#
# output lines should be in '<category> <type> <names>' format
#
do_listbackup_()
{
	cat <<-EOFLISTBACKUP
		config.devices FILE ${DICOM_VAR#$HOME/}
		config.devices DATABASE Target DevServ
		data.mpps DATABASE MPPS
	EOFLISTBACKUP
}

#--- MAIN ------------------------------

check_action_ $1
if [ 0 = $? ]; then
	cmd=$1
	shift
	do_${cmd}_ "$@"

else
	echo "--- Component dicom [ctrl $$]: Bad command: $1" >&2
	exit 1

fi
