#!/bin/bash
#
# findPV
# Author: Shawn Alverson
# Created: 09/26/2013
# Modified: 09/29/2013, S. Alverson
#                Added program specific support and waiting spinner graphic
#
# Usage: findPV [OPTION] [STRING]
# Description: Searches pvlist files for PVs containing a specific string
#

# Initialize variables
PROG[0]=""
FILE=""
SCRIPT=0

# Parse options and inputs
if [ $# -ne 0 ];then
   while getopts ":p:f:sh" Option
   do
     case $Option in
         p  ) PROG=$(echo $OPTARG | awk '{print tolower($0)}')
              if [ "$PROG" == "facet" ] || [ "$PROG" == "lcls" ];then
		  PROG[0]="$OPTARG"
	      elif [ "$PROG" == "xta" ] || [ "$PROG" == "asta" ];then
		  PROG[0]="acctest"
	      elif [ "$PROG" == "all" ];then
		  PROG[0]="facet"
		  PROG[1]="lcls"
		  PROG[2]="acctest"
	      else
	          echo "Invalid program $OPTARG. Options are \"lcls\", \"facet\", \"xta\", \"asta\", or \"all\"."
	          exit 1
	      fi;;
	 f  ) FILE=$OPTARG;;
	 s  ) SCRIPT=1;;  # Script Mode only show ioc and pv names for use in external scripts
	 :  ) echo "Option -$OPTARG requires an argument.  See help (-h) for more info"
	      exit 1;;
	 *  ) echo -e "\nSyntax: findPV [OPTION] [STRING]"
	      echo -e "Options: -p [PROGRAM] Select program (lcls, facet, all). Only works on production servers."
	      echo -e "         -s Script mode.  Only show ioc and pv names for use in external scripts"
	      echo -e "         -h Help\n"
	      echo -e "Note: '%' serves as wildcard for comparison (i.e. 'IN20%TMIT'). '.*' will also work. \n"
              exit 0;;
     esac
   done
   shift $(($OPTIND-1))
fi

if [ $# -eq 0 ]; then echo "Invalid search string."; exit 1; fi
INPUTSTR=$1
# Change user friendly "%" to grep friendly ".*" wildcards
STR=$(echo $INPUTSTR | sed -e 's/\%/\.\*/g')

# Start search
if [ $SCRIPT -ne 1 ]; then
	spinner &                                 # Start waiting spinner
	disown                                    # Disown subscript to supress alerts
	WAITING=$!                                # Save PID for spinner process
fi

ENTRIES=""
for i in "${!PROG[@]}";do
	if [ "${PROG[$i]}" == "" ];then
		# Use environment path if no program given
		DATA_DIR=$IOC_DATA
	elif [ "${PROG[$i]}" == "acctest" ];then
		DATA_DIR="/nfs/slac/g/acctest/epics/ioc/data"
	else
		DATA_DIR="/u1/${PROG[$i]}/epics/ioc/data"
	fi
	# Search for PVs in IOCCOMMON directories
	if [ -d "$DATA_DIR" ];then
		GETSTR=$(egrep -i $STR $DATA_DIR/*/iocInfo/IOC.pvlist)
		if [ "$GETSTR" != "" ];then ENTRIES="$ENTRIES\n$GETSTR"; fi
	fi
done

# Process results
if [ "$ENTRIES" == "" ];then
	if [ -d /proc/$WAITING ];then kill $WAITING &> /dev/null; fi   # Stop waiting spinner discarding stderr
	sleep 0.1 # Sleep long enough for waiting process to fully close
	echo -e "\nNo instances of \"$INPUTSTR\" found.\n"
	exit 0
else
    # Remove unwanted path information
    PVS=$(echo -e "$ENTRIES" | sed -e s_^.*data\/_""_g -e s_/iocInfo/IOC.pvlist:_": "_g -e s_,_""_g)
fi

# Stop waiting spinner
if [ $SCRIPT -ne 1 ]; then
	if [ -d /proc/$WAITING ];then kill $WAITING &> /dev/null; fi
fi

# Display results
LINE=`tput smul`
NOLINE=`tput rmul`
BOLD=`tput bold`
NORMAL=`tput sgr0`

if [ $SCRIPT -eq 0 ]; then
	NUM=$(($(echo "$PVS" | wc -l) - 1))
	S=""
	if [ $NUM -gt 1 ];then S="s"; fi

	echo -e "\n$LINE$BOLD$NUM$NORMAL$LINE instance$S of \"$INPUTSTR\" found$NOLINE"

	IFS=$'\n'
	last_ioc=''
	pvs_in_ioc=''
	for pv in $PVS; do
		curr_ioc=$(echo $pv | awk '{print $1}' | sed s/://g)
		if [[ "$curr_ioc" != "$last_ioc" ]]; then
			if [ "$pvs_in_ioc" != '' ]; then
				echo -e "$pvs_in_ioc" | column -t | grep --color -i "$STR"
			fi
			eng_pv=$(echo "${curr_ioc^^}:CONTACT" | sed s/\-/\:/g)
			engineer=$(caget -t "$eng_pv" 2> /dev/null)
			echo -e "\n$BOLD$curr_ioc$NORMAL - $engineer:"
			last_ioc="$curr_ioc"
			pvs_in_ioc=''
		fi
		pvs_in_ioc="$pvs_in_ioc\n"$(echo $pv | awk '{$1 = ""; print $0; }')
	done
	if [ "$pvs_in_ioc" != '' ]; then
		echo -e "$pvs_in_ioc" | column -t | grep --color -i "$STR"
	fi
	echo
else
	echo -e "$PVS" | awk '{$3 = ""; print $0}' | sed s/:// | column -t | grep --color -i "$STR"
fi

if [ "$FILE" != "" ];then
	if [[ -e "$FILE" ]]; then
		echo -n "File already exists, are you sure you wish to overwrite? (y/n) "
		read ans
		echo
		if [ "$ans" != "y" ]; then echo -e "File not saved.\n"; exit 0; fi
	fi
	touch $FILE
	echo -e "$PVS" | column -t | grep --color -i "$STR" > $FILE
	echo -e "PVs written to file: $FILE.\n"
fi

exit 0
