#!/bin/sh
#################################################################
# Written by Arie Doron                                         #
# Version 2.0                                                   #
# Date: 05.17.2005 12:15                                        #
#                                                               #
#    Improvements (from Version 1):                             #
#       1. Added 'q' for quit in main menu                      #
#       2. Moved selecting destination to the end               #
#       3. Add number of entries found in the screen report     #
#       4. In output file, shows the exact reqest               #
#       5. One more option (by month in a year)                 #
#       6. Verify days (1-31) and month (1-12)                  #
#       7. Scripts runs until you quit                          #
#       8. Show savesets status                                 #
#       9. Show last search result                              #
#################################################################

#set -x
#onstruct temp files
SSLIST=/scitex/version/logs/SSlist.txt
LEGVOL=/scitex/version/logs/VerLegVol.log
PREVPATH=/scitex/version/logs/SSlist.path
LEGERR=0                # Legato error status
SSTRING=                # Since request (2) String
DSTRING=                # Date request (3) String
MSTRING=                # Month request (4) String
VOLNAME=                # Storage for Volume Name
SELECTION=              # Storage for letter selection

# Check host name
HOST=`hostname`

# Get date and time
RDATE=`date| cut -c1-10`
RYEAR=`date | awk '{print $6}'`
RTIME=`date |cut -c12-16`

# Intercept <Ctrl-C> and <Ctrl-Z)
trap 'echo "\ninterrupted. Thank you and Goodbye...\n"; exit' 2 18

# Print report header
Header()
{
echo >> $SSLIST
echo "volume Name\t\t  Date Time\t\t Saveset\t Status \t Name" >> $SSLIST
echo "-----------\t\t  ---------\t\t -------\t ------ \t ----" >> $SSLIST
}

# Check for a valid month ( 1-12 ), returns 1 for success
CkMonth()
{
  MM=$1
  
  if [ $MM -lt 1 -o $MM -gt 12 ]; then
   echo "Month is out of range..."
   return 0
else
  return 1
fi
}

# Check for a valid day ( 1-31 ), returns 1 for success
CkDay()
{
  DD=$1
  if [ $DD -lt 1 -o $DD -gt 31 ]; then
    echo "Day is out of range..."
    return 0
  else
    return 1
  fi
}

# Checks you selected directory, returns 1 for success
CkDest()
{
   Found=0
#   Dest=
 #  if [ -f $PREVPATH ]; then                # Check if Previous path file exist
 #     PREVDEST=`cat $PREVPATH`
 #     DEST=$PREVPATH
 #     echo "Path is: $DEST"
 #     Found=1
 #     return $Found
 #  fi
   
   until [ $Found -eq 1 ]
   do
      FIXED=""                        # If you just press <Enter>
      echo " "
      until [ -n "$FIXED" ]           # if you type nothing, do not exit try again
      do
        echo "Save into:   /dataVolumes/\c"
        read FIXED
      done                    # User typed something     
      Dest=/dataVolumes/$FIXED
      if [ ! -d $Dest ]; then
         echo "\nERR: Destination ( $Dest ) does not exist. Please create path first"
         echo "Destination must be inside the following:"
         echo "`df -k |awk '{print $7}' | grep dataV`"       # Show available dataVolumes
         Dest=
      else
        DEST=$Dest
        echo "$DEST" > $PREVPATH
        Found=1
        return $Found
      fi
   done 
}

# Check if Legato is up and running
CkLegatoUp()
{
#check that Legato is up:
ps -ef |grep nsrexecd |grep -v "grep"  2>&1 > /dev/null
if [ $? != 0 ]; then
   echo "\n Legato is not running... \n"
   echo " Would you like to run Legato (y/n) ?"
   read ANS
   if [ $ANS = 'n' ]; then
     exit 1
   else                 # Not running, start it
     echo " Starting Legato. Please wait....\n " | tee -a $REC_LOG
     `nsrexecd; nsrd`
   fi
fi
}

# Display and read menu options, returns the selected option
ReadSelection()
{
Selection=
until [ -n "$Selection" ]
do
#  clear
  echo '
      +-----------------------------------------------------------------+           
      |    Please select one of the item below:                         |   
      |                                                                 |        
      |    1. List by a paricular volume (fast search)                  |           
      |    2. List by since... (like: since last week)                  |           
      |    3. List by a particular date (slow search)                   |           
      |    4. List by a particular month in a year (slow search)        |
      |                                                                 |
      |    8. List last search result                                   |
      |                                                                 |                      
      |    9. Quit this program                                         |           
      +-----------------------------------------------------------------+
 
      Your selection please (1, 2, 3, 4, 8 or 9): \c'
   read Selection
   # Only the above numbers are allowed. All other keys will redisplay this menu
if [ "$Selection" -eq 1 -o "$Selection" -eq 2 -o "$Selection" -eq 3 -o "$Selection" -eq 4  -o  "$Selection" -eq 8 ]
   then
   SELECTION=$Selection
elif [ "$Selection" -eq 9 ]; then
     echo "quitting..."
     exit 0
else
   Selection=
fi
done
}

# Accomplishes the copy. Exit in an error
FinalCopy()
{
Dest=$DEST
echo "\nCoping the latest two requests to provided destination..."
cp $SCI_LOGS/SSlist* $Dest
if [  "$?" -ne 0 ]; then
   echo "\nERR: Could not copy...\n"
else
   echo "Done coping..."
   echo "Files can be found in ( $Dest ) folder..."
fi
}

# If similar log file there, rename to prev (this scripts allows 2 searches results)
CkPrevFiles()
{
if [ -a $SSLIST ]; then                # if exist, rename it
   echo "\n SSlist.txt exists. Coping current file to _prev" 
   cp $SSLIST /scitex/version/logs/SSlist_prev.txt
fi
}

# Verify Legato volume name, returns 1 for success
VerLegVol()
{
#mminfo -av -r 'volume' |grep arc > $LEGVOL
mminfo -av -r 'volume' > $LEGVOL        # For testing

cat $LEGVOL | 
while read TempVol
do
   if [ "$TempVol" = "$1" ]; then
     FOUND=1
     echo "Legato volume: ( $TempVol ) exists\n"
     break;
   fi
done
return $FOUND
}

# Display and process request for volume, returns 1 for a success
DispReq1()
{   
  VOLNAME=
   FOUND=0
        until [ "$FOUND" -eq 1 ]; do
          echo " "
          echo "Legato Volume Name (Ex: ripro1.archive.023) ... \c"
          read VOLNAME
          VerLegVol $VOLNAME
          if [ "$?" -eq 1 ]; then
            FOUND=1
          else
            echo "No such volume ( $VOLNAME )"          # If no such volume
            VOLNAME=
          fi
        done
   return $FOUND
}

# Display and process request for since... Updates GLOBAL SSTRING
DispReq2()
{   
echo " "
       echo " Here are some or the options:"
       echo " yesterday, last week, last month, last year"
       echo " 2 days ago, 3 days ago, 10 days ago etc."
       echo " 2 weeks ago, 3 weeks ago, 99 weeks ago etc."
       echo "            Your selection ( use <CTRL><C> to quit) ...Since \c"
       read Dt
       until [ -n "$Dt" ]               # Only <Enter> is not accepted
       do
           echo "Try again:  Your selection ( use <CTRL><C> to quit) ...Since \c"
            read Dt
       done
       SSTRING=$Dt
}

# Display and process request for exact date. Updates GLOBAL DSTRING
DispReq3()
{   
       echo " "
       echo "               Query by date (Ex: 03/12/05) ...\c"
       read Dt
       until [ -n "$Dt" ]               # Only <Enter> is not accepted
       do
           echo "Try again:  Query by date (Ex: 03/12/05) ...\c"
            read Dt
       done
       DSTRING=$Dt
}

# Display and process request for a month in a year. Updates GLOBAL MSTRING
DispReq4()
{   
       echo " "
       echo "                  Query by month/year (Ex: 12/05) ...\c"
       read Dt
       until [ -n "$Dt" ]               # Only <Enter> is not accepted
       do
           echo "Try again:  Query by month/year (Ex: 12/05) ...\c"
            read Dt
       done
       MSTRING=$Dt
}

# This function executes Legato for a volume request, returns 1 for error
RptVol()
{
   # Store query result
   VolName=$VOLNAME
   echo "Query Date: $RDATE, $RYEAR $RTIME" > $SSLIST
   echo "    Request: All archives in volume $VolName" >> $SSLIST
   Header;
   ExecVol $VolName
   if [ $?  -ne 0 ]; then
     LEGERR=1
   fi

}

# Executing Legato command with appropriate parameters (according to Volume)
ExecVol()
{
   mminfo -av $1 | awk '{print $1,"\t",$3, $4,"\t", $7,"\t", $8,"\t", $9}' | \
   grep $1 | sed 's/cE/recyclable/' | sed 's/cb/browsable/' | sed 's/cr/recoverable/'  >> $SSLIST
}

# Executing Legato command with appropriate parameters (according Since date)
ExecSince()
{
   mminfo -av -t "$SSTRING" | awk '{print $1,"\t",$3, $4,"\t", $7,"\t", $8,"\t", $9}' | \
   grep $HOST.archive | sed 's/cE/recyclable/' | sed 's/cb/browsable/' | sed 's/cr/recoverable/'  >> $SSLIST
}

# Executing Legato command with appropriate parameters (according to a date or a month in a year)
ExecD()
{
 Dt=$1
 echo "$Dt" > ./DT
echo "Processing your request, please wait..."
 mminfo -av -t $Dt -o t | grep archive | grep -v SC | nawk '{getline var < "./DT"; if ($3 == var) { print $1, "\t",$3, $
4,"\t", $7,"\t", $8,"\t", $9} else
 {break;}} close("./DT")' | sed 's/cE/recyclable/' | sed 's/cb/browsable/' | sed 's/cr/recoverable/'  >> $SSLIST
}

# Executing according to month and year
ExecM()
{
 Dt=$1
echo "Processing your request, please wait..."
 mminfo -av -o t | grep archive | grep -v SC | egrep $Dt | awk '{ print $1, "\t",$3, $4,"\t", $7,"\t", $8,"\t", $9}' | s
ed 's/cE/recyclable/' | sed 's/cb/browsable/' | sed  's/cr/recoverable/'  >> $SSLIST
echo "Processing. Please wait..."
}

# This function executes Legato for since date request. Sets GLOBAL Legato error flag to 1 in case of an error
RptSince()
{
   # Store query result
   Dt="$SSTRING"
   echo "Query Date: $RDATE, $RYEAR $RTIME" > $SSLIST
   echo "     Request: All archives since $DT" >> $SSLIST
   Header;
   ExecSince $Dt
   if [ $? -ne 0 ]; then
      LEGERR=1
   fi
}

# This function executes Legato for particular date. Sets GLOBAL Legato error flag to 1 in case of an error
RptDate()
{
   # Store query result    
   Dt="$1"    
   echo "Query Date: $RDATE, $RYEAR $RTIME" > $SSLIST
   echo "     Request: All archives for $Dt" >> $SSLIST
   Header;
   ExecD $Dt
   if [ $? -ne 0 ]; then
      LEGERR=1
   fi
}

# This function executes Legato for particular month. Sets GLOBAL Legato error flag to 1 in case of an error
RptMonth()
{
   # Store query result  
   Dt="$1"      
   echo "Query Date: $RDATE, $RYEAR $RTIME" > $SSLIST
   echo "     Request: All archives for $Dt" >> $SSLIST
   Header;
   ExecM $Dt
   if [ $? -ne 0 ]; then
      LEGERR=1
   fi
}

# Process user selection
CaseAction()
{
   Selection=$SELECTION
   case  "$Selection" in 
     1 )                        # User pressed 1
        DispReq1;
        RptVol $VOLNAME;
        ;;
    2 )
       # Display the second option menu
       DispReq2;
       DT=$SSTRING
       RptSince $DT;
        ;;
    3 )
       # Display the third option menu
       DispReq3;
       DT=$DSTRING
       Mo=`echo "$DT" | cut -c1-2`
       CkMonth $Mo;
     
       Dy=`echo "$DT" | cut -c4-5`
       CkDay $Dy
       RptDate $DT;      
        ;;
    4 )
       # Display the forth option menu
       DispReq4;
       DT=$MSTRING
       
       Mo=`echo "$DT" | cut -c1-2`              # Take the first 2 digits
       CkMonth "$Mo";                   # Go to CkMonth function
       if [ "$?" -ne 1 ]; then
         echo "Worng date... quitting\n"
         exit 1
       fi

       Yr=`echo "$DT" | cut -c4-5`              # Take the last 2 digits
 
       DT="$Mo/.*/$Yr"
       RptMonth $DT;
        ;;
    8 )
       cat $SSLIST 
        ;;
   * )                          # Any other option, quit
       echo ""
       echo "quitting..."
       exit 1
esac
}

Records()
{
   if [ $LEGERR -eq 0 ]; then
       # Print one line to the screen saying how many entries were found
       TL=`cat $SSLIST |wc -l`
       if [ "$TL" -le 5 ]; then
         echo "\n0 entries were found\n"
         Found=0
       fi
       Sum=`expr $TL - 5`
       if [ $Sum -eq 0 ]; then
         Found=0
       else
         echo "\n  $Sum entries were found\n" |pg
         Found=1
       fi
   else
     echo "\nThere is a Legato error...\n"
     Found=0
   fi
   return $Found
}

# Main program
clear
CkLegatoUp;             # Check if Legato is Up
CkPrevFiles;
while [ "$SEL" != 'q' ]
do
   SEL=
   ReadSelection;          # Display menu and read user input
   SEL="$?"
   CaseAction $SEL;
   Records;
   if [ $? -eq 1 ]; then
     echo "\n Would you like to save current search? (y/n)\c"
     read ANS
     if [ $ANS = 'y' ]; then
       CkDest;                    # Verify Desination 
       FinalCopy;                 # Copy to dataVolume
     fi
   fi
done
