#!/bin/bash


ROOT_DIR="/usr/local/lcls/tools/edm/display"
VERBOSE=false

usage() {
    echo "Usage: `basename $0` [-h] [ -d ROOT_DIR ] [ -v ]" 1>&2 
    echo "    -h Display usage" 1>&2
    echo "    -a Specify area names to search for, separated by commas. Default: BSY0,BSY1,LTU1,UND1,DMP1,FEE1,SYS2"
    echo "    -d Specify alternate root directory. Default: ${ROOT_DIR}" 1>&2
    echo "    -v Verbose output with lists of filenames included. Default: Only display instance counts" 1>&2
}

exit_with_error() {
    usage
    exit 1
}

AREAS=( "BSY0" "BSY1" "LTU1" "UND1" "DMP1" "FEE1" "SYS2" )

while getopts "a:hd:v" options; do
    case "${options}" in
      h) exit_with_error
        ;;
      a)
        AREAS=()
        IFS=',' read -ra USER_AREAS <<< "${OPTARG}"
        for a in "${USER_AREAS[@]}"; do
            AREAS+=( $a )
        done
        ;;
      d)
        ROOT_DIR="${OPTARG}"
        ;;
      v)
        VERBOSE=true
        ;;
      *)
        exit_with_error
        ;;
    esac
done

echo "Running in root directory ${ROOT_DIR}"

if [ -d "${ROOT_DIR}" ]; then
    cd "${ROOT_DIR}"
    for AREA in "${AREAS[@]}"; do
        echo -e "Searching for references to ${AREA} in ${ROOT_DIR}:\n"
        if [ "${VERBOSE}" = true ]; then
            find "${ROOT_DIR}" -type f ! -name '*~*' ! -name '*#*' -print | grep --exclude-dir="CVS" --exclude="*~*" --exclude="*#*" --exclude="*.bak" -rilI "${AREA}" 
            echo
        fi
        AREA_COUNT=`find "${ROOT_DIR}" -type f ! -name '*~*' ! -name '*#*' -print | grep --exclude-dir="CVS" --exclude="*~*" --exclude="*#*" --exclude="*.bak" -rilI "${AREA}" | wc -l` 
        echo -e "    Found ${AREA_COUNT} files with references to ${AREA} in ${ROOT_DIR}\n"
    done
fi
