#!/bin/sh

# $Id: Vols,v 1.6 2007/10/17 20:02:57 zalokar Exp $

#Dump the volume information for each tape library (robot) for the
# tape inventory summary.

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

#First obtain the directory to write the output.
html_dir=`enstore conf $timeout --show crons html_dir`
if [ ! -d "$html_dir" ]; then
    echo HTML directory $html_dir not found.
    exit 1
fi
#If the inventory directory does not exist, create it.
inventory_dir=$html_dir/tape_inventory
if [ ! -d "$inventory_dir" ]; then
    mkdir -p $inventory_dir
fi

#Loop over all the media changers (remember to delete the header line).
enstore conf $timeout --list-media-changers | sed '1d' |
while read line; do
    #Skip Manual and RDD (aka null) media changers.
    echo $line | egrep "Manual|RDD" > /dev/null 2> /dev/null
    if [ $? -eq 0 ]; then
        continue
    fi

    mc=`echo $line | awk '{print $1}'`

    #Get the name of the tape library.
    tape_library=`enstore conf $timeout --show $mc tape_library 2> /dev/null`
    if [ $? -ne 0 ]; then
        #Use the entire line from the --list-media-changers command if
	# the tape_library was not found in the media_changer configuration.
        tape_library=$line
    fi

    #Use just the short name of the media changer converted to upper case.
    tl_name=`echo $mc | tr "." " " | cut -f 1 -d " " | tr '[a-z]' '[A-Z]'`
    #Create the variables that point to the files to output to.
    fname=${tl_name}-VOLUMES
    output_file=$inventory_dir/$fname
    temp_file=$output_file.temp
    
    #If we write to a temp file, and swap in it when we are done, there will
    # not any time when the page is empty becuase the scipt is still writing
    # the file.
    rm -f $temp_file

    echo Starting to making output file for $tl_name.

    #Make sure we know how up-to-date this is.
    echo -e $tl_name Volume List Report: `date` >> $temp_file 2>&1
    echo -e Brought to You by: `basename $0` "\n" >> $temp_file 2>&1
    #Get the volumes!
    enstore media $timeout --list-volumes $mc >> $temp_file 2>&1
    echo -e "\n" >> $temp_file 2>&1
    #Give and end time so we know how long it took.
    echo -e $fname Report Completed: `date` "\n" >> $temp_file 2>&1

    mv $temp_file $output_file   #Do the temp file swap.
    
    echo Done making output file for $tl_name.

    #For backward compatiblity make an html file too.
    echo Starting to making html file for $tl_name.
    rm -f $output_file.html
    cat << EOF >> $output_file.html
<html> <head> <title>$tl_name Volume Status Page</title> </head>
<body>
<body bgcolor="#ffffff" text=#a0a0ff">
<meta http-equiv="Refresh" content="900">
<hr>
<pre>
EOF

    cat $output_file >> $output_file.html

    cat << EOF >> $output_file.html
</pre>
<hr>
<hr>
</body>
EOF
    #End of making the html file.
    echo Done making html file for $tl_name.

done
