#!/bin/sh

# $Id$

#
# Script to return a random file name(s) for tapes in the current inventory.
#  Optionaly, attempt to copy the files from tape using encp (see
#  copy_ran_file).
#

set -u

if [ "${1:-}" = "-x" ] ; then set -xv; shift; fi

if [ "${1:-}" = "-V" ] ; then verbose=1; shift; else verbose=0; fi

if [ "${1:-}" = "-C" ] ; then copyit=1; shift; else copyit=0; fi

if [ "${1:-}" = "-F" ] ; then force_try=1; shift; else force_try=0; fi

#  $1 should be the number of tapes to list/copy.
COUNT=${1:-1}
#  $2 should be one of: "onlylast" or "alsolast" or "onlyfirst" or "alsofirst"
#                       or "onlyfirstlast" or "alsofirstlast" or "onlyran"
WHICH_FILE=${2:-"onlyran"}

if [ "$ENSTORE_CONFIG_HOST"x == x ]; then
   source /usr/local/etc/setups.sh
   if [ -f $HOME/enstore ]; then
      setup -r `cd $HOME/enstore;pwd` enstore
   else
      setup enstore
   fi
fi

#Verify that all of the pnfs mount points in /etc/fstab are mounted before
# continueing.  If /etc/fstab is missing a new mount point, this check
# will still miss it.
check_pnfs_mounts
if [ $? -gt 0 ]; then
   exit 9
fi

here=`pwd`
override_ro="" #Used to audit the state of the write protect tab.
tmp_dir=/tmp

#Make sure to set a timeout.
timeout="--retries 3 --timeout 30"

#First obtain the directory to write the copy output log information.
if [ $copyit -eq 1 ]; then
  ran_log_dir=`enstore conf $timeout --show crons copy_ran_file_log_dir`
  if [ $? -ne 0 ]; then
    echo Error getting copy_ran_file log directory from configuration. 1>&2
    exit 1
  elif [ -z "$ran_log_dir" ]; then
    echo No copy_ran_file log directory in configuration. 1>&2
    exit 1
  fi
  if [ ! -d "$ran_log_dir" ]; then
    mkdir -p "$ran_log_dir"
    if [ $? -ne 0 ]; then
      echo Log directory $ran_log_dir not found. 1>&2
      exit 1
    fi
  fi
  LOGNAME="$ran_log_dir/copy_ran_file"
  if [ ! -f "$LOGNAME" ]; then
    touch "$LOGNAME"
    if [ $? -ne 0 ]; then
        #Use touch's error message.
        exit 1
    fi
  fi
  if [ `id -u` -eq 0 ]; then
    #Make enstore the owner, but don't make it fatal.
    chown enstore "$ran_log_dir"
    chgrp enstore "$ran_log_dir"
    chown enstore "$LOGNAME"
    chgrp enstore "$LOGNAME"
  fi
fi

#Obtain a list of test libraries to ignore.  (ttl = Test Library List)
## Get the information from the configuration.

tll_raw=`enstore conf $timeout --print crons test_library_list 2> /dev/null`
###   If there is no test_library_list then this will be an error.
###   Comment this check out for now.
##if [ $? -ne 0 ]; then
##    echo "Failed to obtain test library list from configuration." 1>&2
##    exit 1
##fi
##
#Remove the line header contents (before the :), remove any empty lines,
# stick single quotes on either side of each item, replace all newlines
# with commas and lastly remove the last comma.
if [ -z "$tll_raw" ]; then
    tll=""
else
    tll=`echo "$tll_raw" | cut -f 2 -d ":" | egrep -v ^$ | sed -e "s/$/'/" -e "s/^/'/" | tr "\n" "," | sed "s/,$//"`
fi
if [ -z "$tll" ]; then
    skip_library_sql=""
else
    if [ $verbose -eq 1 ]; then
	echo "Skipping libraries:" "$tll"
    fi
    skip_library_sql="and library not in ($tll)"
fi

#Make sure the library exists.  Get the list of configured libraries,
# grab just the first part out the output, remove everything after the period
# leaving just the short library name, stick single quotes on either size
# of each item, replace all newlines with commas and lastly remove the last
# comma.
#vll = Valid Library List
vll_raw=`enstore conf $timeout --list-library`
if [ $? -gt 0 ]; then
   echo "Unable to obtain the list of configured libraries." 2>&1
   exit 1
fi
vll=`echo "$vll_raw" | sed '1d' | awk '{print $1}' | tr "." " " | awk '{print $1}' | sed -e "s/$/'/" -e "s/^/'/" | tr "\n" "," | sed "s/,$//"`

VOLS_DEFINED=$tmp_dir/V_D_$$
trap 'echo Cleaning up temporary files. 1>&2;
      if [ -n "${VOLS_DEFINED:-}" -a -w "${VOLS_DEFINED:-}" ]; then
        rm -f "$VOLS_DEFINED";
      fi;
      if [ -n "${TAPE_FILE_LIST_FORMATED:-}" -a -w "${TAPE_FILE_LIST_FORMATED:-}" ]; then
        rm -f "$TAPE_FILE_LIST_FORMATED";
      fi;
      if [ -n "${TAPE_FILE_LIST:-}" -a -w "${TAPE_FILE_LIST:-}" ]; then
        rm -f "$TAPE_FILE_LIST";
      fi;
      if [ -n "${BAD_FILE_LIST:-}" -a -w "${BAD_FILE_LIST:-}" ]; then
        rm -f "$BAD_FILE_LIST";
      fi;
      exit 1;' HUP INT QUIT ABRT ALRM TERM PIPE

#Get the list of suitable tapes for testing.
###8-16-2007: The 'or' of the system_inhibit_1 values to readonly and full
###           should have a third condition.  If the last_access time is
###           older than three months, allow the tape for consideration.
enstore info $timeout --query \
"select label,library,media_type,wrapper,write_protected
from volume where
    label not like '%.deleted' and
    label not like 'CLN%' and
    label not like '%:%' and
    system_inhibit_0 = 'none' and
    ( system_inhibit_1 = 'readonly' or system_inhibit_1 = 'full' or
      last_access < CURRENT_TIMESTAMP - interval '3 months' ) and
    user_inhibit_0 = 'none' and
    extract('epoch' from last_access) <> -1 and
    media_type <> 'null' and
    library in ($vll) and   --Only consider configured libraries.
    library not like '%shelf%' $skip_library_sql and
    system_inhibit_1 not in ('migrated', 'migrating', 'duplicated',
                             'duplicating', 'cloned', 'cloning')
order by label;" \
    | sed '1,2d' > "$VOLS_DEFINED"

N=`wc "$VOLS_DEFINED" | awk '{print $1}'`

if [ $verbose -eq 1 ]; then
    echo "Found $N suitable tapes."
    cat "$VOLS_DEFINED"
fi

if [ $N -eq 0 ]; then
   rm -f "$VOLS_DEFINED"
   exit 1
fi

done=$COUNT
loops=0
RC=0

while [ $done -gt 0 ]; do

  cd $here
  loops=`expr $loops + 1`
  if [ $loops -ge 1000 ]; then
    echo "TOO MANY LOOPS = $loops, EXIT"
    exit 1
  fi

  # choose a random volume from the list
  ran=`python -c "import random;print random.randint(1,"$N")"`
  tape=`head -n $ran "$VOLS_DEFINED" | tail -n 1| awk '{print $1}'`

  # Get up to date information on the tape to make sure we have a chance
  # to read a file.
  if [ $verbose -eq 1 ]; then
    echo `date` enstore info $timeout --vol $tape
  fi
  tinfo=`enstore info $timeout --vol $tape`
  if [ $? -ne 0 ]; then
    echo "Unable to obtain $tape information." 1>&2

    exit 1
  fi
  if [ $verbose -eq 1 ]; then
    echo "$tinfo"
  fi
  #Skip the tape if is is marked deleted, not allowed by an administrator
  # or noaccess by the system.
  if [ `echo $tinfo | egrep -c 'DELETED|NOTALLOWED|NOACCESS'` -ne 0 ]; then
    echo REJECTED $tape is DELETED/NOTALLOWED/NOACCESS
    continue
  fi
  #We need to tell encp to tell the mover to load the tape for read-write
  # mode (full or readonly; migrated too???).  This is so that we can audit
  # the state of the write_protect tab.
  if [ `echo $tinfo | egrep -c "full|readonly|migrated"` -ne 0 ]; then
     override_ro="--override-ro-mount"
  #   echo "override $override"
  fi
  #If the library is not available, pick another one.  Start by pulling
  # out the library name from the volume record.
  library=`echo "$tinfo" | grep library | awk '{print $2}' | tr -d "',"`
  if [ $library = "none" ]; then
    #Skip blank volumes.
    continue
  fi
  #If the library is not available, pick another one.  Start by pulling
  # out the library name from the volume record.
  volume_family=`echo "$tinfo" | grep volume_family | awk '{print $2}' | tr -d "',"`
  if [ $volume_family = "none.none.none" ]; then
    #Skip blank volumes.
    continue
  fi
  #Get the current state of the library.
  raw_lm_status=`enstore library --status $library`
  if [ $? -ne 0 ]; then
    echo "Unable to obtain $library library manager status." 1>&2
    continue
  fi
  lm_status=`echo $raw_lm_status | tr ":" " " | awk '{print $3}' | tr -d "',"`
  #If the state is broken, locked, pause, ignore, noread or moverlock skip it.
  # The expected value is "unlocked", however, allow "nowrite".
  if [ $lm_status != "unlocked" -a $lm_status != "nowrite" ]; then
    echo "Library $library in $lm_status state for volume $tape." 1>&2
    continue
  fi

  #Get a list of all files on the tape.
  TAPE_FILE_LIST="$tmp_dir/${tape}_$$"
  enstore info $timeout --list $tape | sed '1,2d' > "$TAPE_FILE_LIST"
  if [ $? -ne 0 ]; then
    echo "Unable to obtain $tape content information." 1>&2
    exit 1
  fi
  #Truncate the formated tape list information.
  TAPE_FILE_LIST_FORMATED="$tmp_dir/${tape}_$$_"
  if [ -f "$TAPE_FILE_LIST_FORMATED" -a ! -w "$TAPE_FILE_LIST_FORMATED" ]; then
    #Another copy_ran_file is running.
    echo "Skipping already chosen $tape." 1>&2
    rm -f "$TAPE_FILE_LIST" "$TAPE_FILE_LIST_FORMATED"
    continue
  fi
  > "$TAPE_FILE_LIST_FORMATED"  #Truncate the file.
  if [ $? -ne 0 ]; then
    echo "Unable to modify temporary file $TAPE_FILE_LIST_FORMATED." 1>&2
    rm -f "$TAPE_FILE_LIST" "$TAPE_FILE_LIST_FORMATED"
    continue
  fi

  # make sure this volume is still on the readable list.
  match_count=`egrep -c 'DELETED|NOACCESS|NOTALLOWED' "$TAPE_FILE_LIST"`
  if [ $match_count -ne 0 ]; then
    echo `date` REJECTED $tape is DELETED/NOACCESS/NOTALLOED 1>&2
    rm -f "$TAPE_FILE_LIST" "$TAPE_FILE_LIST_FORMATED"
    continue
  fi

  # get list of known bad file bfid's.
  BAD_FILE_LIST="$tmp_dir/bad_list_$$"
  enstore file --show-bad | grep $tape | cut -f 2 -d " " > "$BAD_FILE_LIST"
  #Turn this into an egrep compatible filter string.  (be sure to remember
  # to remove the first " | " from the string.
  bad_filter=`for item in $(cat $BAD_FILE_LIST); do echo -n " |" $item; done | cut -c 2-`
  rm -f "$BAD_FILE_LIST"

  # Get rid of volume information - we already processed that and don't
  # need it anymore. Get rid of all files the user already deleted.
  # We don't want to read these files.  If there aren't any files left,
  # start over with a new tape.  Ignore hidden files and sort the filelist
  # according to location on the tape.  Also, skip known bad files.
  if [ -n "$bad_filter" ]; then
    grep /pnfs "$TAPE_FILE_LIST" | egrep -v 'deleted|  yes /' | grep active | egrep -v "$bad_filter" | grep -v '\/\.' | sort -k4 > "$TAPE_FILE_LIST_FORMATED"
  else
      grep /pnfs "$TAPE_FILE_LIST" | egrep -v 'deleted|  yes /' | grep active | grep -v '\/\.' | sort -k4 > "$TAPE_FILE_LIST_FORMATED"
  fi
  rm -f "$TAPE_FILE_LIST"
  NF=`wc "$TAPE_FILE_LIST_FORMATED" | awk '{print $1}'`
  if [ $NF -gt 0 ]; then
    if [ $verbose -eq 1 ]; then echo `date`: $NF SUITABLE FILES on $tape; fi
  else
    if [ $verbose -eq 1 ]; then echo `date`: NO SUITABLE FILES on $tape; fi
    rm -f "$TAPE_FILE_LIST_FORMATED"
    continue
  fi


    #Grab the first file on the tape.
  case $WHICH_FILE in
    onlyfirst|onlyfirstlast|alsofirst|alsofirstlast)
       # Grab the first file on the random volume.
       file_f=`head -n 1 "${TAPE_FILE_LIST_FORMATED}" | awk '{print $NF,$1,$3,$4,$2}'`
       # Get the first file's bfid.
       first_bfid=`echo $file_f | awk '{print $5}'`
       ;;
  esac

  #Pick a random file on the tape.
  case $WHICH_FILE in
    onlyran|alsofirst|alsolast|alsofirstlast|*)
       # Choose a random file on the random volume.
       ran=`python -c "import random;print random.randint(1,"$NF")"`
       file_r=`head -n $ran "${TAPE_FILE_LIST_FORMATED}" | tail -n 1 | awk '{print $NF,$1,$3,$4,$2}'`
       # Get that file's bfid.
       ran_bfid=`echo $file_r | awk '{print $5}'`
       ;;
  esac

  #Grab the last file on the tape.
  case $WHICH_FILE in
    onlylast|onlyfirstlast|alsolast|alsofirstlast)
       # Grab the first file on the random volume.
       file_l=`tail -n 1 "${TAPE_FILE_LIST_FORMATED}" | awk '{print $NF,$1,$3,$4,$2}'`
       # Get the last file's bfid.
       last_bfid=`echo $file_l | awk '{print $5}'`
       ;;
  esac

  rm -f "$TAPE_FILE_LIST_FORMATED"

  # Make a list of what the user wants.  Valid values are:
  #  "onlylast" or "alsolast" or "onlyfirst" or "alsofirst"
  #  or "onlyfirstlast" or "alsofirstlast" or "onlyran"
  case $WHICH_FILE in
      onlyran)
          thebfids=$ran_bfid
          ;;
      onlyfirst)
          thebfids=$first_bfid
          ;;
      onlylast)
	  thebfids=$last_bfid
          ;;
    onlyfirstlast)
          thebfids="$first_bfid $last_bfid"
          ;;
    alsofirst)
          thebfids="$ran_bfid $first_bfid"
          ;;
    alsolast)
          thebfids="$ran_bfid $last_bfid"
          ;;
    alsofirstlast)
          thebfids="$ran_bfid $first_bfid $last_bfid"
          ;;
      *)
          thebfids=$ran_bfid
          ;;
  esac

  #Make the list of bfids unique.  This avoids repeat reads if the first
  # and/or last file happen to be the randomly chosen file.
  thebfids=`echo "$thebfids" | tr " " "\n" | uniq`

  # ok, just tell the user the name of the file and do another if needed
  # or copy the file to /dev/null if user requested this
  if [ $copyit -eq 0 ]; then
    echo "$thefids"
  else
    echo
    echo "Random volume = $tape"
    echo "Random file = ${file_r-:}"
    echo "First  file = ${file_f-:}"
    echo "Last   file = ${file_l-:}"
    echo

    #Obtain the library that this tape belongs too.
    raw_library=`enstore info $timeout --vol $tape`
    if [ $? -ne 0 ]; then
        echo "Unable to obtain information about $tape." 1>&2
        exit 1
    fi
    library=`echo "$raw_library" | grep library | cut -d' ' -f3`
    library=`echo $library | tr ",'" "  " | sed "s/ //g"`

    #Verify that there is a library manager for this library.
    raw_is_lib_known=`enstore conf $timeout --list-library-manager`
    if [ $? -ne 0 ]; then
        echo "Unable to obtain the list of libraries." 1>&2
        exit 1
    fi
    is_lib_known=`echo "$raw_is_lib_known" | grep $library | wc -l`
    if [ "$is_lib_known" -eq 0 ]; then
        echo "Unable to find ${library}.library_manager." 1>&2
	echo
        #Update the return value and the number of volumes done count.
        RC=`expr $RC + 1`
        done=`expr $done - 1`
        continue
    fi

    #List the number of active volumes.  This will give more meaningful
    # output for the administrators.
    cmd="enstore lib $timeout --vols $library"
    echo $cmd
    vols_at_movers=`eval $cmd`
    if [ $? -ne 0 ]; then
	echo "Unable to determine busy drives for ${library}.library_manager." 1>&2
	echo
        continue
    fi

    echo "$vols_at_movers"
    #If the system is busy, don't start encp.
    busy_movers=`echo "$vols_at_movers" | wc -l`
    #Subract the title line of output.
    busy_movers=`expr $busy_movers - 1`

    #Determine the number of total drives for this library.
    cmd2="enstore mov $timeout --list"
    echo $cmd2
    raw_configured_movers=`eval $cmd2`
    if [ $? -ne 0 ]; then
        echo "Unable to obtain the list of movers for library ${library}." 1>&2
        exit 1
    fi
    configured_movers=`echo "$raw_configured_movers" | grep ${library}.library_manager`
    #Now count the number of lines. (Ignore empty lines.)
    total_movers=`echo "$configured_movers" | egrep -v "^$" | wc -l`

    down_movers=0
    #Obtain the list of down movers.  Remove headers and empty lines.
    raw_servers_down=`enstore sched $timeout --show`
    if [ $? -ne 0 ]; then
        echo "Unable to obtain schedule information." 2>&1
	exit 1
    fi
    servers_down=`echo "$raw_servers_down" | egrep -v " Enstore | -----|^$"`
    #Pull out just the server names.
    echo "$servers_down" | awk '{print $1}' > /tmp/copy_ran_file_servers_down
    #Loop over the configured movers looking for a match to a down mover.
    for mover_line in "$configured_movers"; do
	mover_name=`echo $mover_line | awk '{print $1'}`
        if [ -z "$mover_name" ]; then
            continue
        fi
	grep $mover_name /tmp/copy_ran_file_servers_down > /dev/null
	if [ $? -eq 0 ]; then
            #If the grep returns success (0), increase the down movers
            # count by one.
            down_movers=`expr $down_movers + 1`
        fi
    done
    #Determine the number of drives available right now.
    online_movers=`expr $total_movers - $down_movers`

    #Report the number of drives that are busy and those that exist.
    echo
    echo "Busy Drives: $busy_movers  Total Drives: $total_movers  Down Drives: $down_movers  Online Drives: $online_movers"
    echo

    #There needs to be at least one mover up for this library.
    if [ $online_movers -le 0 ]; then
	echo "Unable to find available movers for ${library}.library_manager." 1>&2
	echo
	continue
    fi

    #This test should compare this number to the number of drives in the
    # library.  If -F was specified on the command line (force_try = 1),
    # we will force choose_ran_file to skip this test and force it to run
    # the encp(s).
    mover_threshold=`expr $online_movers - 1` #Leave one idle.
    if [ $busy_movers -gt $mover_threshold -a $force_try -eq 0 ]; then
	echo "Aborting early from high mover usage."
	echo
	#5 seems like a good number. Its greater than 3 indicating 3 failures.
	# It is not -1, -2, 0, 10 or 7 which have special meaning in the plots.
	#9-10-2002: Edited to return 0 instead of 5.  Emails were being
	# generated that make this the simpliest solution.
	exit 0
    fi

    #Try and read the sample files.
    for b in $thebfids; do
      cmd="encp --skip-pnfs --verbose 10 --bypass-filesystem-max-filesize-check --max-resubmit 7 --delayed-dismount 1 $override_ro --get-bfid $b /dev/null"
      echo $cmd
      eval $cmd
      rc=$?
      RC=`expr $RC + $rc`
    done

    #Log the volume and file(s) tested.
    if [ -w "$LOGNAME" ]; then
      echo `date +"%Y-%m-%d %H:%M:%S"` $tape $library $volume_family $thebfids >> "$LOGNAME"
    else
      echo "No write permission to append to copy log file $LOGNAME." 1>&2
    fi
  fi
  done=`expr $done - 1`
done

# Cleanup after ourselves.
rm -f "$VOLS_DEFINED"
trap "" HUP INT QUIT ABRT ALRM TERM PIPE
cd $here

#Give final message, only if requested.
if [ $verbose -eq 1 -a $copyit -eq 1 ]; then
  echo "The combined exit code for all encps executed is $RC."
elif [ $verbose -eq 1 ]; then
  echo "The exit code is $RC."
fi
exit $RC
