#! /bin/sh

# $Id$

#Dump CMS volumes with only deleted volumes.

#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

#Second obtain the directory to put a link to.
url_dir=`enstore conf $timeout --show crons url_dir`

#Obtain the db port number.
DB_PORT=`enstore conf $timeout --show database dbport`
if [ -z "$DB_PORT" ]; then
    echo "dbport not found in configuration."
    exit 1
fi

#Obtain the db name.
DB_NAME=`enstore conf $timeout --show database dbname`
if [ -z "$DB_NAME" ]; then
    echo "dbname not found in configuration."
    exit 1
fi

#Obtain the db host.
DB_HOST=`enstore conf $timeout --show database dbhost`
if [ -z "$DB_HOST" ]; then
    echo "dbhost not found in configuration."
    exit 1
fi

#Obtain the db user/role.
DB_USER=`enstore conf $timeout --show database dbuser`   #dbuser_reader?
if [ -z "$DB_USER" ]; then
    echo "dbuser not found in configuration."
    exit 1
fi

#Create the variables that point to the files to output to.
fname=CMS_VOLUMES_WITH_ONLY_DELETED_FILES
output_file=$inventory_dir/$fname
temp_file=$inventory_dir/.$fname$$.temp
trap "rm -f $temp_file; exit 1" HUP INT QUIT ABRT ALRM TERM

#If we write to a temp file, and swap in it when we are done, there will
# not be any time when the page is empty becuase the scipt is still writing
# the file.
rm -f $temp_file

#Make sure we know how up-to-date this is.
echo -e Migration Report: `date` > $temp_file 2>&1
echo -e Brought to You by: `basename $0` "\n" >> $temp_file 2>&1

psql -p $DB_PORT -h $DB_HOST -U $DB_USER $DB_NAME -c "select * from cms_volume_with_only_deleted_files order by label" -o  $temp_file

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