cmd=$(fc -nl -1)
#!/bin/bash
source $TOOLS/script/ENVS64.bash
source $TOOLS/script/use_python3.sh

fac=$(echo $FACILITY_ROOT | awk -F'/' '{print $NF}')

WAIT=3
NAME="%"
ERR_OUT="0"
RET_IOC="0"

usage(){
	echo "Usage:" 1>&2
	echo "	invalidPVs-Net.bash [ -e ] [ -i ] [ -w WAIT ] [ -a NAME ]" 1>&2
	echo "" 1>&2
	echo "Options:" 1>&2
	echo "	-h          Show this message and exit" 1>&2
	echo "	-e          Print PV name error making it invalid" 1>&2
	echo "	-i          Print IOC containing incorrect PV name" 1>&2
	echo "	-w WAIT     Passes WAIT as wait time argument to eget command" 1>&2
	echo "	-a NAME     Calls eget command looking for PVs using -a name=NAME" 1>&2
	echo "	            More information on eget calls can be found in README" 1>&2

}
exit_abnormal(){
	usage
	exit 1
}

while getopts ":eiw:a:" options; do
	case "${options}" in
		e) ERR_OUT="1";;
		i) RET_IOC="1";;
		w) WAIT=${OPTARG}
			re_isanum='^[0-9]+$'
			if ! [[ $WAIT =~ $re_isanum ]] ; then
				echo "Error: WAIT must be a positive, whole number."
				exit_abnormal
			fi;;
		a) NAME=${OPTARG};;
		:) echo "Error: -${OPTARG} requires an argument."
			exit_abnormal;;
		*) exit_abnormal;;
	esac
done

echo $cmd
if [ "$NAME" = "%" ]; then
	eget -ts ds -w 60 -a name=% | sort | \
        (cd $TOOLS/script/ValidatePVs \
        && python invalidPVs.py \
        input_files/devices.json \
        input_files/${fac}_areas.json \
        $ERR_OUT \
        $RET_IOC)
else
	eget -ts ds -w $WAIT -a name=$NAME | sort | \
        (cd $TOOLS/script/ValidatePVs \
        && python invalidPVs.py \
        input_files/devices.json \
        input_files/${fac}_areas.json \
        $ERR_OUT \
        $RET_IOC)

fi
exit 0
