#!/bin/ksh
#
# Component: etc
#
# Description:
#  System wide control script
#
# Last Updated     : $Author$
# Update Date Time : $Date$
# RCS File Name    : $RCSfile$
# RCS Revision     : $Revision$
# Locked by        : $Locker$
# Symbolic name    : $Name$
# State            : $State$

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

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

COMPONENTS="LOG OPENSSL JAVAKIT MYSQL IMAGEMAGICK WEB BACKEND PCRE POCO EXTTOOLS ICONV DESKTOPAPPS VIEWER VIEWERDEFAULTS PLUGINS CURL DRWATSON APACHE TASKD PROTOBUF WEBCL"

typeset -l COMPONENTS_S
COMPONENTS_S="$COMPONENTS"

typeset -l COMPONENTS_FLAT_S
COMPONENTS_FLAT_S="$COMPONENTS"

#--- FUNC ------------------------------
do_shell_()
{

	SUPPORT_DOMAIN='localhost'
	if [ -f '/etc/imagemed-base/setenv.sh' ]; then
		SRCTEMP=`mktemp`
		if [ $? -ne 0 ]; then
			echo "Fatal error: can't create tempfile!" >&2
		else
			if bash -c ". /etc/imagemed-base/setenv.sh; . \$base_include_dir/registration; get_server_info > $SRCTEMP" && \
				. $SRCTEMP; then
				
				SUPPORT_DOMAIN=$support_domain
			else
				echo "Warning: can't query SiteMan server info!" >&2
			fi
		
			rm -f $SRCTEMP
		fi
		unset SRCTEMP
	fi

	[ ! -d $HOME/var      ] && mkdir $HOME/var      2>/dev/null
	[ ! -d $HOME/var/conf ] && mkdir $HOME/var/conf 2>/dev/null
 
	# virtual hosting support

	SERVERNAME="`hostname -f`" # the canonical name of this server
	SERVERIP="`hostname -i | sed 's/ /\n/g' | grep -m1 -E -o '([0-9]{1,3}[\.]){3}[0-9]{1,3}'`"  # the canonical IP of the server, and exclude IPv6 addressess
	BINDIP="0.0.0.0"          # daemons should bind to this IP

	unset JSERV_BIND JSERV_PORT JSERV_HOST MYSQL_BIND MYSQL_TCP_PORT MYSQL_HOST

	# virthost.sh can override these variables

	if [ -f "$HOME/var/conf/virthost.sh" ]; then
		. "$HOME/var/conf/virthost.sh"
	fi

	cat <<-EOI
		COMPONENTS="$COMPONENTS"
		COMPONENTS_S="${COMPONENTS_S}"
		COMPONENTS_FLAT_S="${COMPONENTS_FLAT_S}"
		DATA=$HOME/data
		VAR=$HOME/var
		TMP=$HOME/tmp
		ETC=$HOME/etc
		MYSQL_ON=true
		MED_USER=`id -nu`
		MED_UID=`id -u`
		USER=`id -un`
		ASROOT="/usr/local/etc/asroot.\$USER/asroot"

		RUN=\$VAR/run
		CONF=\$VAR/conf                         #instead of DCMTK_VAR in the future
		PRESERVE=\$VAR/preserve
		BACKUP_VAR=\$VAR/backup

		DISK_FULL_FLAG_FILE=\$VAR/DISK_FULL

		HOME=$HOME

		SERVERNAME="$SERVERNAME"
		SERVERIP="$SERVERIP"
		BINDIP="$BINDIP"

		SUPPORT_DOMAIN=$SUPPORT_DOMAIN

	EOI
	# HOME: For exporting only

	typeset -l compo

	for Compo in ${COMPONENTS}; do
		compo="$Compo"
		cat <<-EOI
			${Compo}_HOME=$HOME/component/$compo
		EOI
	done

} #do_shell_()

do_crontab_()
{
	# Get time for starting cleanup.sh from crontabSchedule settings
	[ -f "$CONF/crontabSchedule.shi" ] && . $CONF/crontabSchedule.shi
	[ -z "$EtcCleanup" ] && EtcCleanup="24 03"

	cat <<-EOI
		$EtcCleanup * * * $ETC/cleanup.sh >/dev/null 2>&1
	EOI
	[ -f $VAR/conf/crontab ] && cat $VAR/conf/crontab 

} #do_crontab_()

do_start_()
{
	[ ! -d "$VAR" ] && mkdir $VAR 2>/dev/null
	[ ! -d "$TMP" ] && mkdir $TMP 2>/dev/null
	[ ! -d "$ETC" ] && mkdir $ETC 2>/dev/null
	[ ! -d "$DATA" ] && mkdir $DATA 2>/dev/null

	[ ! -d "$RUN" ] && mkdir $RUN 2>/dev/null
	[ ! -d "$CONF" ] && mkdir $CONF 2>/dev/null
	[ ! -d "$PRESERVE" ] && mkdir $PRESERVE 2>/dev/null
	[ ! -d "$BACKUP_VAR" ] && mkdir $BACKUP_VAR 2>/dev/null

	touch $RUN/medsrv.run
#	/usr/bin/logger -p $LOG_OPER_FACILITY.info -t "rcstart[$$]" "INFO OTHER start system - - - - - - - - - - - medsrv_started"

	# initialize shared memory & semaphores for taskd

	if [ -n "$TASKD_DATA" ] ; then
		[ ! -d $TASKD_DATA ] && mkdir $TASKD_DATA
	fi

	$TASKD_HOME/initshared

} #do_start_()

do_stop_()
{

	#close shared memory & semaphores
	$TASKD_HOME/closeshared

	rm $RUN/medsrv.run
#	/usr/bin/logger -p $LOG_OPER_FACILITY.info -t "rcstop[$$]" "INFO OTHER stop system - - - - - - - - - - - medsrv_stopped"

} #do_stop_()


do_capture_()
{
	echo
	ps auxwww
	top -H S n2 b
}

do_monitor_()
{
  local mode="$1"
	TERM=linux
	export TERM
	top -S -n1 -b | head -11 | sed 's;,;, ;g' | awk '
	{

		for (i=0;i<NF-1;i++) if ($(i)=="load" && $(i+1)=="average:")
			{ pl0=$(i+2); pl1=$(i+3); pl2=$(i+4); 
				gsub(",","",pl0);
				gsub(",","",pl1);
				gsub(",","",pl2);
				print "proc_load0="pl0"\nproc_load1="pl1"\nproc_load2="pl2 ;
			}
	}

	$2 == "processes:" {
		print "number_of_sleeping_proc="$3"\nnumber_of_running_proc="$5"\nnumber_of_zombie_proc="$7 ;
	}

# RH4 version:
	$1 == "Tasks:" {
		print "number_of_sleeping_proc="$6"\nnumber_of_running_proc="$4"\nnumber_of_zombie_proc="$10 ;
	}
 
	$1 == "total" {
		gsub("%","");
		cpu=$2+$3+$4+$5+$6;
		io=$7;
		idle=$8;
		print "proc_cpu="cpu"\nproc_iowait="io"\nproc_idle="idle ; 
	}

# CentOS7 version included - v8.0.10 runs ONLY on CentOS7
	$1 == "Cpu(s):" || $1 == "%Cpu(s):" {
		gsub("%","");
		cpu=$2+$4+$6+$10+$12;
		io=$10;
		idle=$8;
		print "proc_cpu="cpu"\nproc_iowait="io"\nproc_idle="idle ;
	}

	# print memory in MiB
        $1 == "KiB" && $2 == "Mem" {
		print "proc_mem="$8/1024
        }
        $1 == "MiB" && $2 == "Mem" {
		print "proc_mem="$8
        }
        $1 == "GiB" && $2 == "Mem" {
		print "proc_mem="$8*1024
        }
        $1 == "TiB" && $2 == "Mem" {
		print "proc_mem="$8*1024*1024
        }
        $1 == "PiB" && $2 == "Mem" {
		print "proc_mem="$8*1024*1024*1024
        }
        $1 == "EiB" && $2 == "Mem" {
		print "proc_mem="$8*1024*1024*1024*1024
        }
	'

	# print actual memory in MiB
	free -m | grep -i "Mem" | awk '{ print "proc_mem_actual="$3 }'
	if [ "$mode" != "snapshot" ] ; then
		df -P $DATA | tail -n 1 | awk '{
			printf "percent_of_used_disk_on_data_partition=%1.2f\n", 100-$4*100/$2 ;
		}'
		
		df -P $TMP | tail -n 1 | awk '{
			printf "percent_of_used_disk_on_tmp_partition=%1.2f\n", 100-$4*100/$2 ;
		}'
	fi
	# read the partition lines from the disk_info file | but only once each partition
	partitionLines=$(grep 'FS=' $VAR/disk_info | sort --unique)
	# remove the 'FS=' from the lines, leaving only the partition paths in each line
	partitions=${partitionLines//"FS="/""}

	# get current time | cut out minutes only:
	minuteText=$(date +"%T" | awk -F':' '{print $2}')
	# cast minute text to number
	minutes=$(($minuteText))
	# modulo 5: this will decide which disks should be checked this time
	minuteMod=$(($minutes % 5))
	# get partition data | remove the output list header
	# awk: only print lines NR%5==minutes%5, replace '/' to '_' with gsub, calculate percentage from total and available columns
	actPartition=$(awk -v minuteMod=$minuteMod 'NR%5==minuteMod' <<< "$partitions")
	
	if [ -n "$actPartition" ] ; then
		df -P $actPartition | tail -n +2 | awk '{
		gsub(/:|\//,"_",$1); printf "iostat_util_%s=%1.2f\n", $1, 100-$4*100/$2 ;
		}'
	fi
}


#
# List files/tables to be backed up grouped by categories
#
# output lines should be in '<category> <type> <names>' format
#
do_listbackup_()
{
	sCONF=${CONF#$HOME/}
	cat <<-EOFLISTBACKUP
		nobackup.nobackup FILE ${BACKUP_VAR#$HOME/} $sCONF/setenv.* $sCONF/crontabSchedule.shi ${DISK_FULL_FLAG_FILE#$HOME/} ${RUN#$HOME/}
		config.server FILE $sCONF/commonnames.ls $sCONF/serverid.cfg $sCONF/site.conf $sCONF/virthost.sh
		config.system FILE $sCONF/crontabSchedule.cfg $sCONF/crontab $sCONF/backupAliases.cfg $sCONF/charset.cfg
	EOFLISTBACKUP
}

#--- MAIN ------------------------------
check_action_ $1
if [ 0 = $? ]; then
	do_$1_ $2

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

fi
