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

print_usage() {
   echo " "
   echo "Usage:"
   echo "    Fpalette [ -help | -d | -l | -more ]  palette_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 Palette files available, enter:"
   echo "    Fpalette '*'"
   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 .spk
if ! echo "${template}" | grep -q '\.spk' ; then
   template="${template}*.spk"
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 palfile in ${filelist} ; do
            descript=`cd ${subdir} ; grep -i ' description: ' ${palfile} | sed -e 's/\! [dD][eE][sS][cC][rR][iI][pP][tT][iI][oO][nN]: //'`
            echo "${palfile}: ${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

