#! /bin/sh

# $Id$

#Dump the progress made in duplicating failed multiple copies and
# retro-actively making multiple copies.

#Get all the common stuff for migration, duplication and cloning reporting.
mig_com=`which migration_common 2> /dev/null`
if [ -z $mig_com ]; then
    #When run interactively, bash was picking the wrong version of
    # migration_common.  Even when 'which' was able to find the correct
    # one with the same environment.
    #
    #If 'which' didn't find it, next try the path of this script.

    mig_com=`dirname $0`/migration_common
    if [ ! -x "$mig_com" ]; then
        #If this fails, fall back to the old way.
	mig_com=migration_common
    fi
fi
source $mig_com

#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
#If the inventory directory does not exist, create it.
plots_dir=$html_dir/migration_summary
plots_link=$plots_dir/plot_enstore_system.html

#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

#Get the temporary directory to use.
temp_dir=`enstore conf $timeout --show crons tmp_dir`
if [ ! -d "$temp_dir" ]; then
    temp_dir=/tmp
fi

#Create the variables that point to the files to output to.
fname=MULTIPLE_COPY_SUMMARY
old_output_file=$inventory_dir/$fname  #ASCII and HTML were both once created.
output_file=$inventory_dir/$fname.html
temp_file=$temp_dir/$fname$$.temp

#Remove the temporary file on failure.
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 any time when the page is empty becuase the scipt is still writing
# the file.
rm -f $temp_file $old_output_file

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

echo                                     >> $temp_file 2>&1
echo "=================================" >> $temp_file 2>&1
echo "Multiple Copy File Family Summary" >> $temp_file 2>&1
echo "=================================" >> $temp_file 2>&1
echo                                     >> $temp_file 2>&1

echo "Creating Multiple Copy Summary" `date`

echo "The original_files counts refer to active files located on volumes still available to the system." >> $temp_file 2>&1
echo >> $temp_file 2>&1

psql -p $DB_PORT -h $DB_HOST -U $DB_USER $DB_NAME -c "
SELECT *, (original_files - duplicated_files) AS non_duplicated_files
FROM
    (SELECT media_type, storage_group, file_family,
            sum(original_files_count) AS original_files,
            sum(duplicated_files_count) AS duplicated_files
     FROM
         (SELECT id, media_type, storage_group, file_family
          FROM volume
          WHERE volume.system_inhibit_0 != 'DELETED'
              AND volume.library NOT LIKE 'shelf-%' -- Only for tapes in robot
              AND volume.file_family NOT LIKE '%/_copy/__' ESCAPE '/'
          ) AS volume_info
     INNER JOIN
         (SELECT volume.id,
                 count(file_info.bfid) AS original_files_count,
                 count(fcm.alt_bfid) AS duplicated_files_count
          FROM volume
          INNER JOIN
              (SELECT bfid, volume
               FROM file
               WHERE file.deleted = 'n'
               ) AS file_info
               ON file_info.volume = volume.id
          LEFT JOIN
              (SELECT file_copies_map.*
               FROM file_copies_map
               LEFT OUTER JOIN migration
                   ON (migration.src_bfid = file_copies_map.bfid)
               ) AS fcm
               ON fcm.bfid = file_info.bfid
          WHERE
              -- Limit per volume file counts to just the same volume
              -- conditions as in the volume_info sub-select.
              -- Cost is more if the results of these filters are previously
              -- cached and then reused here.
              volume.system_inhibit_0 != 'DELETED'
              AND volume.library NOT LIKE 'shelf-%' -- Only for tapes in robot
              AND volume.file_family NOT LIKE '%/_copy/__' ESCAPE '/'
          GROUP BY volume.id
          ) AS file_counts
          ON file_counts.id = volume_info.id
     GROUP BY media_type, storage_group, file_family
     ORDER BY media_type, storage_group, file_family
     ) AS t1
WHERE duplicated_files > 0 ;
" >> $temp_file 2>&1

echo                                    >> $temp_file 2>&1
echo "================================" >> $temp_file 2>&1
echo "Failed Multiple Copies Remaining" >> $temp_file 2>&1
echo "================================" >> $temp_file 2>&1
echo                                    >> $temp_file 2>&1

echo "Creating Failed Multiple Copies" `date`

psql -p $DB_PORT -h $DB_HOST -U $DB_USER $DB_NAME -c "
select active_file_copying.bfid,
remaining as \"copies remaining\",
active_file_copying.time as \"waiting since\"
from active_file_copying
left join file_copies_map on active_file_copying.bfid = file_copies_map.bfid
where remaining > 0 and time < CURRENT_TIMESTAMP - interval '24 hours' and exists
( select 1 from file where file.bfid = active_file_copying.bfid and file.deleted='n')
order by time"  >> $temp_file 2>&1

echo                                  >> $temp_file 2>&1
echo "==============================" >> $temp_file 2>&1
echo "Failed Multiple Copies Skipped" >> $temp_file 2>&1
echo "==============================" >> $temp_file 2>&1
echo                                  >> $temp_file 2>&1

echo "Creating Failed Multiple Copies Skipped" `date`

echo "These are:" >> $temp_file 2>&1
echo "1) original copies where the write failed" >> $temp_file 2>&1
echo " or" >> $temp_file 2>&1
echo "2) original copies that have already been migrated" >> $temp_file 2>&1
echo >> $temp_file 2>&1

psql -p $DB_PORT -h $DB_HOST -U $DB_USER $DB_NAME -c "
select active_file_copying.bfid,
       active_file_copying.time as waiting_since,
       case when (select deleted from file
                  where file.bfid = active_file_copying.bfid
                    and file.deleted = 'u') is not NULL
            then 'failed'
            when (select pnfs_id from file
                  where file.bfid = active_file_copying.bfid
                  limit 1) = ''
            then 'failed'
            when (select dst_bfid from migration
                  where migration.src_bfid = active_file_copying.bfid
                  limit 1) is not NULL
            then 'migrated'
            when (select system_inhibit_0 from volume,file
                  where active_file_copying.bfid = file.bfid
                    and file.volume = volume.id
                  limit 1) = 'DELETED'
            then 'volume deleted'
            when (select fcm2.bfid from file_copies_map as fcm2
                  where fcm2.alt_bfid = active_file_copying.bfid
                  limit 1) is not NULL
            then 'original migrated'
            else ' '
       end
from active_file_copying
left join file_copies_map on active_file_copying.bfid = file_copies_map.bfid
where remaining < 0
order by time;
" >> $temp_file 2>&1

echo                                                         >> $temp_file 2>&1
echo "=====================================================" >> $temp_file 2>&1
echo "Failed Multiple Copies Written Retro-actively per Day" >> $temp_file 2>&1
echo "=====================================================" >> $temp_file 2>&1
echo                                                         >> $temp_file 2>&1

echo "Creating Failed Multiple Copies Written Retro-actively per Day" 'date'

#This pulls the timestamp right out of the bfid.
psql -p $DB_PORT -h $DB_HOST -U $DB_USER $DB_NAME -c "
select date(TIMESTAMP 'epoch' + cast(substring(file_copies_map.alt_bfid from '([0-9]*).{5}$') as int) * interval '1 second') as day,
       count(file_copies_map.alt_bfid) as multiple_copies
from file_copies_map,active_file_copying
where file_copies_map.bfid = active_file_copying.bfid
group by day
order by day
;
" >> $temp_file 2>&1

echo                                  >> $temp_file 2>&1
echo "==============================" >> $temp_file 2>&1
echo "Failed Multiple Copies per Day" >> $temp_file 2>&1
echo "==============================" >> $temp_file 2>&1
echo                                  >> $temp_file 2>&1

echo "The day is the date the user's multiple copy failed." >> $temp_file 2>&1
echo "The multiple_copies_failed is the number of failures on that day." >> $temp_file 2>&1
echo "The next three columns show what state these failures are in, respectively:  " >> $temp_file 2>&1
echo "   copy retro-actively made, skipped or remaining to do." >> $temp_file 2>&1
echo >> $temp_file 2>&1

echo "Creating Failed Multiple Copies" `date`

psql -p $DB_PORT -h $DB_HOST -U $DB_USER $DB_NAME -c "
select date(time) as day,
       count(active_file_copying.bfid) as mulitple_copies_failed,
       count(case remaining
                  when 0
                  then file_copies_map.alt_bfid
                  else NULL
                  end) as failures_made,
       count(case when remaining < 0
             then active_file_copying.bfid
             else NULL
             end) as failures_skipped,
       count(case when remaining > 0
             then active_file_copying.bfid
             else NULL
             end) as failures_remaining
from active_file_copying
left join file_copies_map on active_file_copying.bfid = file_copies_map.bfid
group by day
having date(time) <= date(current_timestamp - interval '24 hours')
order by day
;
" >> $temp_file 2>&1


#Turn out the html page.
make_html "$tl_name Multiple Copies Summary Page" $temp_file $output_file $url_dir

#Remove the temp file.
rm -f $temp_file
