#!/bin/bash

#-----------------------------------------------------------------------
#			User parameters
#-----------------------------------------------------------------------
#Verify tool path
VERIFY_TOOL="/home/mdm/workspace/nexecs/test/tools/fitsverify"
CHECK_STRING="conform to the FITS format"

NO_FILE_ERROR="failed to find or open the following file"

FATAL_ERROR="Fatal"

EOF_ERROR="End-of-file"

#-----------------------------------------------------------------------
#			Verify script
#-----------------------------------------------------------------------
if [ "$1" == "CHECK" ]; then
	res=$($VERIFY_TOOL 2>&1)
	check=$(echo $res | grep "$CHECK_STRING" | wc | awk '{print $1}')
	if [ "$check" -ge "1" ]; then
		echo "CHECK OK"
	else
		echo "NOT OK"
	fi
	exit 0
else
	#Check regular expression -> fatal
	file=$1
	file_name=${file##*/}
	if [[ ! "${file_name,,}" =~ ^[^\.].*\.(fits|fts).*$ ]]; then
		echo "FATAL"
		exit 0
	fi

	#if fits verify tools exists -> fatal
	if [ ! -x $VERIFY_TOOL ]; then
		echo "FATAL"
		exit 0
	fi

	#if fits file not exists -> fatal
	if [ ! -f $1 ]; then
		echo "FATAL"
		exit 0
	fi

	#Check with fits verify
	res=$($VERIFY_TOOL $1 2>&1)

	#if fitsverify return fatal error -> wait
	fatal=$(echo $res | grep "$FATAL_ERROR" | wc | awk '{print $1}')
	if [ "$fatal" -ge "1" ]; then
		echo "WAIT"
		exit 0
	fi

	#if fitsverify return end of file -> wait
	eof=$(echo $res | grep "$EOF_ERROR" | wc | awk '{print $1}')
	if [ "$eof" -ge "1" ]; then
		echo "WAIT"
		exit 0
	fi

	#else -> ok
	echo "OK"
	exit 0
fi
#-----------------------------------------------------------------------
