#!/bin/tcsh -f
#------------------------------------------------------------------------------
#   2005/01/11
#      Written by Tsan-Lung Hsieh, Institute of Physics, Academia Sinica
#      Create metadata python script for BeamExe output file
#  input: defined by the environment variable $TheOutputFile
#  output: metadata file , name is defined by the environment variable METADATA
#  assume ecrc is available w/o setups !
#------------------------------------------------------------------------------
set name = "GenRecoMetaV6.csh"

# used to show time stamp
alias tsecho 'echo `date "+%Y/%m/%d %H:%M:%S"` = '

tsecho $name TheOutputFile=$TheOutputFile
tsecho $name METADATA=$METADATA

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

# the variables from ExtractPhys.py

setenv Phys_FileSize    0
setenv Phys_First_Run   0
setenv Phys_First_Event 0
setenv Phys_Last_Run    0
setenv Phys_Last_Event  0
setenv Phys_Events      0
setenv Phys_RunSections ""


# get the latest pid of ProductionExe
ls ProductionExe.* >& /dev/null
if $? == 0 then
	setenv pid `ls -tr ProductionExe.* | 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 `$BIN_DIR/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

#------------------------------------------------------------------------------
#
#------------------------------------------------------------------------------
if ( FileSize != 0 ) then
  tsecho $name "$BIN_DIR/cdfopr/ExtractPhys.py --file=$TheOutputFile"
  $BIN_DIR/cdfopr/ExtractPhys.py --file=$TheOutputFile
  set rc=$?
    
  tsecho $name "rc=$rc"
    
  tsecho $name "source source_Phys_$TheOutputFile"
  cat    source_Phys_${TheOutputFile}    
 source  source_Phys_${TheOutputFile}

endif

# no empty allowed, give some string
setenv crashRecord 'null'
if ( $ExcludeEventsList != "none" ) then
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
endif
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_DSPACK,
    SAM.attrFirstEvent         : ${Phys_First_Event},
    SAM.attrLastEvent          : ${Phys_Last_Event},
    SAM.attrEventCount         : ${Phys_Events},
    SAM.attrCrcValue           : '${CrcValue}L',
    SAM.attrCrcType            : SAM.CRC_Adler32Type,
    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.attrDataTier           : '$DATA_TIER',
    SAM.attrConsumerProcessId  : ${CPID},
    SAM.attrParents            : ['${bnTheFile}'],
    SAM.attrWorkGroup          : 'test',
    SAM.attrParams             : params,
})

EOF

tsecho === ${METADATA} ===
cat ${METADATA}
tsecho === ${METADATA} ===


if ${FLAG_DECLARE_META} == 1 then
	# declare for file ${TheOutputFile}
	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
			tsecho sam declare file ${TheOutputFile} with ${METADATA} successfully
			setenv Flag 0
			break
		endif

		sleep 10
	end

	if ${Flag} == 1 then
		tsecho sam declare file ${TheOutputFile} failed
		$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
	endif
else
	# declare file ${TheOutputFile}
	tsecho sam declare file ${METADATA}
endif


exit 0

