#!/bin/ksh
#
# Component: archive
#
# Description:
#  Control script of component archive
#
# Last Updated     : $Author: tnemeth $
# Update Date Time : $Date: 2014/04/16 11:48:52 $
# RCS File Name    : $RCSfile: ctrl,v $
# RCS Revision     : $Revision: 1.22 $
# Locked by        : $Locker:  $
# Symbolic name    : $Name:  $
# State            : $State: Exp $

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

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

#--- FUNC ------------------------------
do_shell_()
{
	cat <<-EndOfInlineData
		ARCHIVE_DIR=\$VAR/archive
		ARCHIVE_VAR=\$VAR/arch
		ARCHIVE_HOME=$HOME/component/archive
		ARCHIVETBL=Archive
		ARCHIVE_TEMPDIR=\$VAR/archive/noarchive
		DAYS2KEEP_ARCHIVE_TEMP=30
	EndOfInlineData

} #do_shell_()

# Checks if releasereference.cfg contains handlers
# for cases specific references, and add them if necessery
check_and_add_releasecfg_()
{
	if [ ! -f "${CONF}/releasereference.cfg" ] ; then
		sed "s;\$HOME;$HOME;" ${ARCHIVE_HOME}/cfg/releasereference.cfg >> ${CONF}/releasereference.cfg
	else
		# create grep pattern from existing configuration
		GREPP=`awk -vORS=" " '/^#/ {next} ($1 != "") {print "-e ^" $1}' $CONF/releasereference.cfg`
		# make sure that $CONF/releasereference.cfg is writable
		chmod u+w $CONF/releasereference.cfg
		eval "grep -v -e ^# $GREPP $ARCHIVE_HOME/cfg/releasereference.cfg" | sed "s;\$HOME;$HOME;" >> $CONF/releasereference.cfg
	fi
}

do_start_()
{
	# Check and create ARCHIVE_VAR
	if [ ! -d "$ARCHIVE_VAR" ] ; then
		mkdir $ARCHIVE_VAR

		# move archive settings from $CONF/self.rec
		if [ -f "$CONF/self.rec" ] ; then
			grep -e "^Archive" -e "^MountPoint" $CONF/self.rec >> ${ARCHIVE_VAR}/archive.cfg
			if [ $? -eq 0 ] ; then
				grep -v -e "^Archive" -e "^MountPoint" $CONF/self.rec >> ${CONF}/self.rec.new
				mv $CONF/self.rec $TMP/self.rec.save
				mv ${CONF}/self.rec.new $CONF/self.rec
			fi
		fi

		# move $CONF/archive.cfg content to ${ARCHIVE_VAR}/archive.cfg
		if [ -f "$CONF/archive.cfg" ] ; then
			sed -e 's;^NOARCHIVE_DIR=;ArchiveTempDir=;' -e's;^DAYS2KEEP_ARCHIVE_TEMP=;Days2KeepArchiveTemp=;' \
					$CONF/archive.cfg >> ${ARCHIVE_VAR}/archive.cfg
			[ $? -eq 0 ] && mv $CONF/archive.cfg $TMP/archive.cfg.save
		fi

		# move archive rules settings from $CONF/archive_rules.rec to ${ARCHIVE_VAR}/archive.cfg
		if [ -f "$CONF/archive_rules.rec" ] ; then
			cat $CONF/archive_rules.rec >> ${ARCHIVE_VAR}/archive.cfg
			[ $? -eq 0 ] && mv $CONF/archive_rules.rec $TMP/archive_rules.rec.save
		fi

		# move dicomMedia.cfg from $CONF to ${ARCHIVE_VAR}
		if [ -f "$CONF/dicomMedia.cfg" ] ; then
			mv $CONF/dicomMedia.cfg ${ARCHIVE_VAR}/dicomMedia.cfg
		fi
	fi

	#Check WarningLimit, ChangeLimit, EmptyMountPoints, StopArchive fields in archive.cfg
	if [ -f "$ARCHIVE_VAR/archive.cfg" ] ; then
		. $ARCHIVE_VAR/archive.cfg
		if [ -z $WarningLimit ] ; then
			echo "WarningLimit=\"60\"" >> $ARCHIVE_VAR/archive.cfg 
		fi
		if [ -z $ChangeLimit ] ; then
			echo "ChangeLimit=\"85\"" >> $ARCHIVE_VAR/archive.cfg 
		fi
		if [ `grep "^EmptyMountPoints" $ARCHIVE_VAR/archive.cfg | wc -l` -eq 0 ] ; then
			echo "EmptyMountPoints=\"\"" >> $ARCHIVE_VAR/archive.cfg 
		fi
		if [ -z $StopArchive ] ; then
			echo "StopArchive=\"97\"" >> $ARCHIVE_VAR/archive.cfg 
		fi
	fi
	
	needCheckTable="false"

	# Check and create ARCHIVE if needed
	if [ -f "$ARCHIVE_VAR/archive.cfg" ] ; then
		. $ARCHIVE_VAR/archive.cfg
		if [ "$Archive" = "yes" ] ; then
			[ ! -d "$ARCHIVE_DIR" ] && echo "$ARCHIVE_DIR does not exist"
			needCheckTable="true"
		else
			# Check if archive table exist
			$MYSQL_HOME/bin/mysqlshow $DBNAME $ARCHIVETBL >/dev/null 2>&1
			[ $? -eq 0 ] && needCheckTable="true"
		fi
	fi

	if [ "$needCheckTable" = "true" ] ; then
		# Create / alter Archive table
		CLASSPATH=$CLASSPATH:$HOME/component
		export CLASSPATH
		$JAVA_HOME/bin/java ${CASES_HOME#$HOME/component/}.SqlTables $ARCHIVETBL
		RES=$?
		
		if [ $RES -ne 0 ] ; then
			echo "Error checking, creating or fixing SQL tables"
			return $RES
		fi
	fi 


	# Check Archive property in archive.cfg and if it is yes, then change to readonly
	# It was decided to not to change Archive to readonly automatically for there might be archives
	# which will exist in the future [v6.1] (Eg. a Juke Box archive mounted via NFS)
	#
	# Support should set the Archive attribute to readonly and the NO_DELETE flag should also be set
	# for v6.x
	
	# Check if releasereference.cfg and necessary entries exists
	check_and_add_releasecfg_

	# Move new ignoretags to existing ignoretags file
	if [ -f "$ARCHIVE_VAR/ignoretags" ] ; then
		chmod +w $ARCHIVE_VAR/ignoretags
		customSorted="$TMP/ignoretags.custom.sorted.$$"
		builtinSorted="$TMP/ignoretags.builtin.sorted.$$"
		sort $ARCHIVE_VAR/ignoretags > "$customSorted"
		sort $ARCHIVE_HOME/ignoretags > "$builtinSorted"
		diff "$customSorted" "$builtinSorted" | sed -n "s;^> ;;p" >> $ARCHIVE_VAR/ignoretags
		rm "$customSorted" "$builtinSorted" 2>/dev/null
	fi

} #do_start_()

do_beforesubmit_()
{
	do_stop_

} #do_beforesubmit_()

do_aftersubmit_()
{
	do_start_

} #do_aftersubmit_()

do_crontab_()
{
	# Get time from crontabSchedule settings for starting crontab jobs
	[ -f "$CONF/crontabSchedule.shi" ] && . $CONF/crontabSchedule.shi
	[ -z "$CleanNoArchive" ] && CleanNoArchive="13 01"
	[ -z "$CheckArchiveMount" ] && CheckArchiveMount="32 04"

	cat <<-EOI
		$CleanNoArchive * * * $ARCHIVE_HOME/cleanNoArchive.sh 2>&1
		$CheckArchiveMount * * * $ARCHIVE_HOME/checkArchiveMount.sh 2>&1
	EOI
	if [ -f "$ARCHIVE_VAR/archive.cfg" ] ; then
		. "$ARCHIVE_VAR/archive.cfg"
		if [ "$Archive" = "readonly" -a "$DoMerge" = "true" ] ; then
			cat <<-EOI
				03-58/5 * * * * $ARCHIVE_HOME/scheduleMerge.sh 2>&1
			EOI
		fi
	fi

} #do_crontab_()


#
# List files/tables to be backed up grouped by categories
#
# output lines should be in '<category> <type> <names>' format
#
do_listbackup_() {
	cat <<-EOFLISTBACKUP
		nobackup.nobackup FILE ${VAR#$HOME/}/Archive_merge.lst
		data.archive FILE ${ARCHIVE_DIR#$HOME/}
		data.archive DATABASE Archive
		config.archive FILE ${ARCHIVE_VAR#$HOME/}
	EOFLISTBACKUP
}


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

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

fi
