#!/bin/bash

# $Id$

# Generate the VOLUME_CROSS_CHECK inventory web page.
# This script is very Fermilab specific.

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

gang=$(gang)

# Make sure to set a timeout.
timeout='--timeout 10 --retries 3'

# First obtain the directory to write the output.
inventory_dir=`enstore conf $timeout --show crons html_dir`/tape_inventory
if [ ! -d $inventory_dir ]; then
    echo Inventory directory $inventory_dir not found.
    exit 1
fi

# Create the variables that point to the files to output to.
fname=VOLUME_CROSS_CHECK
output_file=$inventory_dir/$fname
temp_file=$output_file.temp	# Write to this then swap it into place.

# If we write to a temp file, and swap it in when we are done, there will
# not be any time when the page is empty because the script is still writing
# the file.
rm -f $temp_file
if [ -L $output_file ]; then
   # Should VOLUME_CROSS_CHECK be a symbolic link to the ecron .output file
   # we should handle removing it before we write an actual file there.
   rm -f $output_file
fi

# obtain list of valid libraries
libs=( $(enstore conf --list-lib|awk 'NR > 1 {print substr($1,1,match($1,/\./) -1)}'|sort -u) )

# This is for easier redirection of all the stdout output.
(

    # Make sure we know how up-to-date this is.
    echo -e Volume Cross Check Report: `date`
    echo -e Brought to You by: `basename $0` "\n"

    ##
    # All tapes are in SL8500 robots
    # It does not matter which LSMs the bots place the tapes within a specific robot
    #
    # ACSLS
    # host     SL8500s ACS LSMs  Instances                 InventoryFiles
    # ==========================================================================
    # fntt-gcc  1,2,4   0  0-11  stken, gccen              SL8500G1-VOLUMES.html
    # fntt2     3,5     1  0-7   cdfen, d0en, gccen, stken SL8500F1-VOLUMES.html
    # fntt      6       2  0-3   cdfen, d0en, dmsen, stken SL8500GS-VOLUMES.html
    #
    # Cleaning tapes are CLN -- not sure if we need to track these?
    ##

    ##
    # Specific tape labels and list of robots for each instance
    #
    # Each of the labels will match starting with the given strings.
    # Each of the robots will list as the applicable robots for the instance.
    ##
    case $gang in
    aggren)
	labels="MAX07"
	robots="GS"
	;;
    stken)
	labels="FUJ,MAX0[^7],V,TEST29,TST07[4-9],TST098,TST189,TST19[01],TTC02[578],TTC071"
	robots="F1,G1,GS"
	;;
    cdfen)
	labels="I,TST098,TST10[012],TST19[4-9],TTC02[36]"
	robots="F1,GS"
	;;
    d0en)
	labels="P,TST099,TST19[23]"
	robots="F1,GS"
	;;
    dmsen)
	labels="FUJ,MAX,TST,TTC"
	robots="GS"
	;;
    gccen)
	labels="T,V"
	robots="F1,G1"
	;;
    *)
	echo "silo-check: error: cannot process instance $gang" >&2
	exit 1
    esac

    echo -e "Contingent on data produced by:\n\trobot_inventory:"
    ls -l $inventory_dir/SL8500*-VOLUMES.html

    echo -e "\tinventory:"
    ls -l $inventory_dir/VOLUMES_DEFINED
    echo


    ##
    # How the different formats appear for various ACSLS query/display commands and enstore inventory
    # 
    # for "query drive" (ACSLS 8), each line in the silo inventory is in one of four formats:
    #   vol   home		acs, lsm, panel, row, col	type
    #   vol   in drive	acs, lsm, panel, drive		type
    #   vol   in transit	acs, lsm, panel, row, col	type
    #   vol   in transit	acs, lsm, panel, drive		type
    # where type is one of LTO-400G, LTO-800G, LTO-1.5T, LTO-CLNU, T10000CC, T10000T2
    #
    # for "display" (ACSLS 8), each line in the silo inventory has ten fields:
    #   Vol_id  Acs  Lsm  Panel  Row  Column  Pool   Status    Media     Type
    # where
    #   Status is one of dismount, eject, enter, mount, home, in_drive, move, missing, absent, ejected
    #   Media is one of LTO-400G, LTO-800G, LTO-1.5T, T10000T2
    #   Type is one of data, clean
    #
    # all lines of enstore inventory have ten fields, in this format:
    #   vol   avail   system_inhibit   user_inhibit   library   wp_status	mounts   volume_family
    # where each inhibit takes two fields (including parentheses)
    #
    # there should be no deleted volumes in VOLUMES_DEFINED
    ##

    ##
    # Begin processing
    ##

    # List volumes in the current instance (gang) in all SL8500 robots
    awk -v volStr="(^${labels//,/|^})" '
        $0 ~ /^$/ {next}
        $0 ~ /^</ {next}
        NF == 4 && $1 ~ volStr && $0 !~ /ejected/ {print $1}' $inventory_dir/SL8500*-VOLUMES.html |sort > /tmp/rail-volumes

    # List volumes defined in enstore for the current instance (gang)
    awk 'NR > 3 && NF == 10 && $7 !~ /(null|disk|shelf)/ {print $1}' $inventory_dir/VOLUMES_DEFINED |\
	sort >/tmp/vols-defined

    # tapes in any SL8500, but not in enstore
    echo
    echo "--------------------------------------------------------------------------------------------------------------------"
    echo "$gang Tapes (${labels//,/*|}*) in any SL8500 ($robots) that are not fully declared to enstore"
    comm -23 /tmp/rail-volumes /tmp/vols-defined >/tmp/rail-not-enstore
    fgrep -f /tmp/rail-not-enstore $inventory_dir/SL8500*-VOLUMES.html

    ### Following old code not sure what to do with at present,iperf -s was commented out in original script
    #echo
    #echo "--------------------------------------------------------------------------------------------------------------------"
    #echo "Tapes not in any category"
    #egrep -v "^$|^<|DG [0-9][0-9][0-9]" $inventory_dir/STK-VOLUMES.html | grep -v "        0, [01],"

    # tapes in enstore, but not in the robots
    echo
    echo "--------------------------------------------------------------------------------------------------------------------"
    echo "Tapes declared to enstore that are not in the SL8500s ($robots)"
    sort -mu /tmp/rail-volumes >/tmp/robot-volumes
    comm -23 /tmp/vols-defined /tmp/robot-volumes >/tmp/enstore-not-robot
    fgrep -f /tmp/enstore-not-robot $inventory_dir/VOLUMES_DEFINED

    ### Have not verified the following really works
    # tapes apparently in more than one robot, whether in enstore or not, ie, duplicate names
    echo
    echo "--------------------------------------------------------------------------------------------------------------------"
    echo "Tapes that are apparently in more than one robot"
    sort -m /tmp/rail-volumes | uniq -d | while read vol; do
	grep -h $vol $inventory_dir/{VOLUMES_DEFINED,{SL8500F1,SL8500G1,SL8500GS}-VOLUMES.html}
    done

    ### Do we want to continue to exclude migrated tapes?
    echo
    echo "--------------------------------------------------------------------------------------------------------------------"
    echo "Tapes in NOACCESS or NOTALLOWED state (except those 'migrated')"
    awk 'NR > 3 && NF == 10 && $3 !~ /none/ && $4 !~ /migrated/' $inventory_dir/VOLUMES_DEFINED

    ### Verified the following works -- after rewrote it
    # This will catch any tapes in a library that is not configured
    echo
    echo "--------------------------------------------------------------------------------------------------------------------"
    echo "Tapes in invalid library"
    echo "Valid libraries are: ${libs[@]}"

    awk '
        BEGIN {
            ##
            # build array of valid library names
            ##
            cmd = "enstore conf --list-lib"
            while ((cmd|getline) > 0) {
                if ($1 ~ /\./) {
                    libs[substr($1,1,match($1,/\./) -1)] = 1
                }
	    }
            #for( x in libs) {
            #   print x
            #}
        }
        NR > 3 && NF == 10 && $NF !~ /^test\./ &&
            $7 !~ /(null|disk|shelf)/ && !($7 in libs) {
             print
        }
        ' $inventory_dir/VOLUMES_DEFINED
    echo
    echo "--------------------------------------------------------------------------------------------------------------------"

    ##
    # End
    ##

    date

) | tee $temp_file 2>&1

mv $temp_file $output_file	# Do the temp file swap.
