#!/bin/tcsh

#   2005/01/11
#      Written by Tsan-Lung Hsieh, Institute of Physics, Academia Sinica
#      Create metadata python script for BeamExe output file
#   7 Nov 05  Modified by Aidan and Bernd for CalibExe... and then generalised...

# get binary ecrc to calculate CRC

# used to print with timestamp
alias tsecho 'echo `date "+%Y/%m/%d %H:%M:%S"` = '

setenv MESSENGER $WORK_DIR/bin/$BFARCH/cdfprd/messenger.py

# get the latest pid of CslibExe
ls -tr CalibExe.* >& /dev/null
if $? == 0 then
        setenv pid `ls -tr CalibExe.* | tail -n 1 | awk -F. '{print $2}'`
else
	setenv pid 0
endif


if ( -f ${TheOutputFile} ) then
	# file size of TheOutputFile, KB
	setenv FileSize `find ${TheOutputFile} -printf %k`

	# CRC value of TheOutputFile
	setenv CrcValue `ecrc ${TheOutputFile} | tail -n 1 | awk '{print $2}'`
else
	setenv FileSize 0
	setenv CrcValue 0
endif


if ! $?TS_START then
	setenv TS_START `date '+%m/%d/%Y %H:%M:%S'`
endif


if ! $?TS_END then
	setenv TS_END `date '+%m/%d/%Y %H:%M:%S'`
endif



# no empty allowed, give some string
setenv crashRecord 'null'
foreach line (`cat ${ExcludeEventsList}`)
	setenv run `echo $line | awk -F, '{print $1}'`
	setenv event `echo $line | awk -F, '{print $2}'`
	setenv record `echo $line | awk -F, '{print $3}'`

	setenv crashRecord "${crashRecord}|${run},${event},${record}"
end
tsecho crashRecord is ${crashRecord}


# no empty allowed, give some string
setenv Comments 'null'
if $?DHInputCount then
	setenv Comments "${Comments}|DHInputCount:${DHInputCount}"
endif
tsecho Comments is ${Comments}


cat << EOF > ${METADATA}
import SAM
from SamFile.SamDataFile import SamDataFile
from SamStruct.SamTime import SamTime
from SamStruct.Params import Params

params = Params({
	'production' : {
		'Pid'		: '${pid}',
		'Jobid'		: '${jid}',
		'SectionId'     : '${sid}',
		'nodeName'	: '${Hostname}',
		'projectName'	: '${SF_SAM_PROJECT}',
		'stationName'	: '${SF_SAM_STATION}',
		'crashRecord'	: '${crashRecord}',
		'exeVersion'	: '${SRT_BASE_RELEASE}',
		'Comments'	: '${Comments}',
	},
})

sample = SamDataFile({
    SAM.attrFileName           : '${TheOutputFile}',
    SAM.attrFileSize           : '${FileSize}KB',
    SAM.attrFileType           : SAM.DataFileType_PhysicsGeneric,
    SAM.attrFileFormat         : SAM.DataFileFormat_ROOT,
    SAM.attrFirstEvent         : ${Metadata_First_Run},
    SAM.attrLastEvent          : ${Metadata_Last_Event},
    SAM.attrEventCount         : ${Metadata_Events},
    SAM.attrCrcValue           : '${CrcValue}L',
    SAM.attrCrcType            : SAM.CRC_Adler32Type,
    SAM.attrDataTier           : 'reconstructed',
    SAM.attrStartTime          : SamTime('${TS_START}','%m/%d/%Y %H:%M:%S'),
    SAM.attrEndTime            : SamTime('${TS_END}','%m/%d/%Y %H:%M:%S'),
    SAM.attrPhysicalDatastream : '${rawDataStream}',
    SAM.attrConsumerProcessId  : ${CPID},
    SAM.attrParents            : ['${bnTheFile}'],
    SAM.attrWorkGroup          : 'test',
    SAM.attrParams             : params,
})

EOF

# show up metadata
tsecho === ${METADATA} ===
cat ${METADATA}
tsecho === ${METADATA} ===


if ${FLAG_DECLARE_META} == 1 then
    # declare for file ${TheOutputFile}

    # here we test the sam db server is alive or not
    #setup sam -q farm1_prd
    #sam ping dbserver --server=${SAM_DB_SERVER_NAME} --corbaCallTimeout=10 --retryInterval=10  --retryMaxCount=6

    setenv Flag 1
    foreach try ( first second final )
        tsecho ${try} try to sam declare file
        tsecho sam declare file ${METADATA}
               sam declare file ${METADATA}
        if $? == 0 then
            setenv Flag 0
            break
        endif

        sleep 10
    end

    if ${Flag} == 1 then
        tsecho sam declare file ${TheOutputFile} with ${METADATA} failed
        setenv rsStatus 1

        $MESSENGER -b "Fatal error to do sam declare file ${TheOutputFile}"
	$MESSENGER -b "The output file ${TheOutputFile} had been fcp out successfully"
	$MESSENGER -b "Search ${METADATA}, register it in SAM manually"
	$MESSENGER -b "Execute: sam declare file ${METADATA}"
        $MESSENGER -t "Fatal error in sam declare file ${TheOutputFile}"
        $MESSENGER -s
    else
        tsecho sam declare file ${TheOutputFile} with ${METADATA} successfully
        setenv rsStatus 0
    endif
else
    # declare file ${TheOutputFile}
    tsecho sam declare file ${METADATA}

    setenv rsStatus 0
endif


exit ${rsStatus}

