#! /bin/sh
# Fpattern file_template    
# determine if FERRET pattern files matching template are currently on-line
# by searching the paths in FER_PALETTE

print_usage() {
   echo " "
   echo "Usage:"
   echo "    Fpattern [ -help | -d | -l | -more ]  pattern_file_template"
   echo  " "
   echo "where options include: "
   echo "    -help    print this help message and exit"
   echo "    -d       generate filename list with descriptions (default)"
   echo "    -l       generate long listing without descriptions"
   echo "    -more    display files matching the given template using more"
   echo " "
   echo "These options precede the file template.  Files matching the"
   echo "given template are then listed, or displayed using more if"
   echo "the -more option is used.  All options are mutually exclusive."
   echo "To see all of the Pattern files available, enter:"
   echo "    Fpattern '*'"
   echo "It is important to have the quotes around any asterisks"
   echo "in the file template."
   echo " " 
}

#check for proper amount of args.  One arg is the filename or template. 
if [ $# -lt 1 ] || [ $# -gt 2 ]; then
   print_usage
   exit 1
fi

# check for help flag
if echo "$1" | grep -q '^-h' ; then
   print_usage
   exit 1
fi

if [ $# -eq 1 ]; then
   option=""
   template="$1"
else
   option="$1"
   template="$2"
fi

# check to see if file contains .pat
if ! echo "${template}" | grep -q '\.pat' ; then
   template="${template}*.pat"
fi

found=0
for subdir in ${FER_PALETTE}; do
   filelist=`cd "${subdir}" ; find * -maxdepth 0 -type f -name \*"${template}"\* -print`
   if [ -n "${filelist}" ]; then
      echo "* * * * * * * * in ${subdir}"
      if [ -z "${option}" ] || [ "${option}" = "-d" ]; then
         for patfile in ${filelist} ; do
            descript=`cd ${subdir} ; grep -i ' description: ' ${patfile} | sed -e 's/\! [dD][eE][sS][cC][rR][iI][pP][tT][iI][oO][nN]: //'`
            echo "${patfile}: ${descript}"
         done
      elif [ "${option}" = "-l" ]; then
         ( cd "${subdir}" ; /bin/ls -l ${filelist} )
      elif [ "${option}" = "-m" ] || [ "${option}" = "-more" ]; then
         ( cd "${subdir}" ; more ${filelist} )
      else
         echo "Invalid option: ${option}"
         print_usage
         exit 1
      fi
      echo " " 
      found=1
   fi
done

if [ $found -eq 0 ]; then
   echo "No files matching ${template} were found"
fi

