#! /bin/sh

# $Id$

# This file should not be used directly by the administrator.  It should
# only be sourced by migration_summary, duplication_summary and/or
# cloning_summary.  It provides variables and functions common to all three.

#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


summary()
{
## Note: This sql works as long as migrate.py/duplicate.py use the volume
## clerk set_system_migrated()/set_system_duplicated() function(s) to set
## the system_inhibit_1 value.  
psql -p $DB_PORT -h $DB_HOST -U $DB_USER $DB_NAME -c "
select media_type, sum(migrating) as migrating, sum(migrated) as migrated,
       sum(migration_started) as migration_started,
       sum(migrated_closed_not_shelved) as migrated_closed_not_shelved,
       sum(migrated_closed_shelved) as migrated_closed_shelved,
       sum(duplicating) as duplicating, sum(duplicated) as duplicated,
       sum(duplication_started) as duplication_started,
       sum(duplicated_closed_not_shelved) as duplicated_closed_not_shelved,
       sum(duplicated_closed_shelved) as duplicated_closed_shelved,
       sum(remaining_to_start_migrating) as remaining_to_start_migrating,
       sum(remaining_to_finish_migrating) as remaining_to_finish_migrating,
       sum(remaining_to_scan_and_close) as remaining_to_scan_and_close,
       sum(blank_volumes) as blank_volumes,
       sum(cloning_volumes) as cloning_volumes,
       sum(multiple_copy_volumes) as multiple_copy_volumes,
       sum(total) as total,
       round(((CASE WHEN sum(total) > 0
            THEN (sum(migrated_closed_not_shelved) + 
                  sum(migrated_closed_shelved) +
                  sum(duplicated_closed_not_shelved) + 
                  sum(duplicated_closed_shelved))
                  / (sum(total) - sum(blank_volumes) - sum(cloning_volumes) -
                     sum(multiple_copy_volumes))
            ELSE 0
       END) * 100), 2) as percentage_done
       -- The reason for this outer select is to combine all disk volumes
       -- onto one line.  Disk volumes have many different sizes and in
       -- order to split LTO1 and LTO2 from 3480 too, this extra select
       -- level is needed.  This also has the added benifit of combining
       -- any media_type that has some number of tapes set to the wrong
       -- capacity_bytes.
from (
select /* It should be as simple as just using the media_type. However,
          LTO1 and LTO2 at FNAL are both set as 3480 do to limitations
          in the AML/2 when it was first put into use. */
       /*media_type,*/
       CASE WHEN media_type = '3480' and capacity_bytes = '107374182400'
            THEN 'LTO1'
            WHEN media_type = '3480' and capacity_bytes = '214748364800'
            THEN 'LTO2'
            WHEN media_type = '3480' and capacity_bytes < 100
            THEN NULL    --Cleaning tape; skip it.
            ELSE media_type
       END as media_type,
       CASE WHEN media_type = 'disk'
            THEN -1  --Trick all disk volumes onto one line.
            ELSE capacity_bytes
       END as capacity_bytes,
       count(distinct CASE WHEN system_inhibit_1 = 'migrating'
                           THEN label
                           ELSE NULL
                      END) AS migrating,
       count(distinct CASE WHEN system_inhibit_1 = 'migrated'
                           THEN label
                           ELSE NULL
                      END) AS migrated,
       count(distinct CASE WHEN system_inhibit_1 in ('migrating', 'migrated')
                           THEN label
                           ELSE NULL
                      END) AS migration_started,
       count(distinct CASE WHEN system_inhibit_1 = 'migrated'
                                /* Make sure that at least one destination
                                   has been scanned. */
                                and (select count(*)
                                     from migration_history
                                     left join volume v2 on v2.id = migration_history.dst_vol_id
                                     where migration_history.src_vol_id = volume.id
                                       and migration_history.closed_time is not NULL
                                       /* Ingore recycled destination volumes. */
                                       and v2.system_inhibit_0 != 'DELETED'
                                     limit 1) > 0
                                /* Reject if any destination volumes have
                                   not been scanned. */
                                and (select count(*)
                                     from migration_history
                                     left join volume v2 on v2.id = migration_history.dst_vol_id
                                     where migration_history.src_vol_id = volume.id
                                       and migration_history.closed_time is NULL
                                       /* Ingore recycled destination volumes. */
                                       and v2.system_inhibit_0 != 'DELETED') = 0
                                and volume.sum_wr_access - volume.sum_wr_err > 0 --skip blank tapes
                                and library not like '%shelf%'
                           THEN label
                           ELSE NULL
                      END) AS migrated_closed_not_shelved,
       count(distinct CASE WHEN system_inhibit_1 = 'migrated'
                                /* Make sure that at least one destination
                                   has been scanned. */
                                and (select count(*)
                                     from migration_history
                                     left join volume v2 on v2.id = migration_history.dst_vol_id
                                     where migration_history.src_vol_id = volume.id
                                       and migration_history.closed_time is not NULL
                                       /* Ingore recycled destination volumes. */
                                       and v2.system_inhibit_0 != 'DELETED'
                                     limit 1) > 0
                                /* Reject if any destination volumes have
                                   not been scanned. */
                                and (select count(*)
                                     from migration_history
                                     left join volume v2 on v2.id = migration_history.dst_vol_id
                                     where migration_history.src_vol_id = volume.id
                                       and migration_history.closed_time is NULL
                                       /* Ingore recycled destination volumes. */
                                       and v2.system_inhibit_0 != 'DELETED') = 0
                                and volume.sum_wr_access - volume.sum_wr_err > 0 --skip blank tapes
                                and library like '%shelf%'
                           THEN label
                           ELSE NULL
                      END) AS migrated_closed_shelved,
       count(distinct CASE WHEN system_inhibit_1 = 'duplicating'
                           THEN label
                           ELSE NULL
                      END) AS duplicating,
       count(distinct CASE WHEN system_inhibit_1 = 'duplicated'
                           THEN label
                           ELSE NULL
                      END) AS duplicated,
       count(distinct CASE WHEN system_inhibit_1 in ('duplicating', 'duplicated')
                           THEN label
                           ELSE NULL
                      END) AS duplication_started,
       count(distinct CASE WHEN system_inhibit_1 = 'duplicated'
                                /* Make sure that at least one destination
                                   has been scanned. */
                                and (select count(*)
                                     from migration_history
                                     left join volume v2 on v2.id = migration_history.dst_vol_id
                                     where migration_history.src_vol_id = volume.id
                                       and migration_history.closed_time is not NULL
                                       /* Ingore recycled destination volumes. */
                                       and v2.system_inhibit_0 != 'DELETED'
                                     limit 1) > 0
                                /* Reject if any destination volumes have
                                   not been scanned. */
                                and (select count(*)
                                     from migration_history
                                     left join volume v2 on v2.id = migration_history.dst_vol_id
                                     where migration_history.src_vol_id = volume.id
                                       and migration_history.closed_time is NULL
                                       /* Ingore recycled destination volumes. */
                                       and v2.system_inhibit_0 != 'DELETED') = 0
                                and volume.sum_wr_access - volume.sum_wr_err > 0 --skip blank tapes
                                and library not like '%shelf%'
                      THEN label
                      ELSE NULL
                      END) AS duplicated_closed_not_shelved,
       count(distinct CASE WHEN system_inhibit_1 = 'duplicated'
                                /* Make sure that at least one destination
                                   has been scanned. */
                                and (select count(*)
                                     from migration_history
                                     left join volume v2 on v2.id = migration_history.dst_vol_id
                                     where migration_history.src_vol_id = volume.id
                                       and migration_history.closed_time is not NULL
                                       /* Ingore recycled destination volumes. */
                                       and v2.system_inhibit_0 != 'DELETED'
                                     limit 1) > 0
                                /* Reject if any destination volumes have
                                   not been scanned. */
                                and (select count(*)
                                     from migration_history
                                     left join volume v2 on v2.id = migration_history.dst_vol_id
                                     where migration_history.src_vol_id = volume.id
                                       and migration_history.closed_time is NULL
                                       /* Ingore recycled destination volumes. */
                                       and v2.system_inhibit_0 != 'DELETED') = 0
                                and volume.sum_wr_access - volume.sum_wr_err > 0 --skip blank tapes
                                and library like '%shelf%'
                      THEN label
                      ELSE NULL
                      END) AS duplicated_closed_shelved,
       count(distinct CASE WHEN volume.sum_wr_access - volume.sum_wr_err > 0 /*skip blanks*/
                                and system_inhibit_1 not in ('migrated',
                                                             'duplicated',
                                                             'cloned',
                                                             'migrating',
                                                             'duplicating',
                                                             'cloning')
                                and library not like '%shelf%'
                                /* Skip multiple coipes. */
                                and file_family not like '%/_copy/_%' escape '/'  --match literal underscores
                           THEN label
                           ELSE NULL
                      END) AS remaining_to_start_migrating,
       count(distinct CASE WHEN volume.sum_wr_access - volume.sum_wr_err > 0 /*skip blanks*/
                                and system_inhibit_1 not in ('migrated',
                                                             'duplicated',
                                                             'cloned',
                                                             'cloning')
                                and (library not like '%shelf%' or
                                     system_inhibit_1 in ('migrating',
                                                          'duplicating'))
                                /* Skip multiple coipes. */
                                and file_family not like '%/_copy/_%' escape '/'  --match literal underscores
                           THEN label
                           ELSE NULL
                      END) AS remaining_to_finish_migrating,
       count(distinct CASE WHEN volume.sum_wr_access - volume.sum_wr_err > 0 /*skip blanks*/
                                /* Skip multiple coipes. */
                                and file_family not like '%/_copy/_%' escape '/'  --match literal underscores
                                and ((system_inhibit_1 not in ('migrated',
                                                              'duplicated',
                                                              'cloned',
                                                              'cloning')
                                      and
                                      library not like '%shelf%')
                                     or
                                      system_inhibit_1 in ('migrating',
                                                           'duplicating')
                                     or
                                     ( /* At least one needs to be NULL for
                                        this to still be remaing to complete */
                                      ((select count(*)
                                        from migration_history
                                        left join volume v2 on v2.id = migration_history.dst_vol_id
                                        where src_vol_id = volume.id
                                          and closed_time is NULL
                                          /* Ingore recycled destination volumes. */
                                          and v2.system_inhibit_0 != 'DELETED') > 0
                                      or
                                       /* A scan has not yet been started. */
                                       (select count(*)
                                        from migration_history
                                        left join volume v2 on v2.id = migration_history.dst_vol_id
                                        where migration_history.src_vol_id = volume.id
                                          /* Ingore recycled destination volumes. */
                                          and v2.system_inhibit_0 != 'DELETED') = 0
                                      )
                                      and volume.system_inhibit_1 in 
                                           ('migrated', 'duplicated')
                                     ))
                           THEN label
                           ELSE NULL
                      END) AS remaining_to_scan_and_close,
       count(distinct CASE WHEN /* Skip tapes where the first write failed. */
                            volume.sum_wr_access - volume.sum_wr_err = 0
                            and library not like '%shelf%'
                           THEN label
                           ELSE NULL
                      END) as blank_volumes,
       count(distinct CASE WHEN system_inhibit_1 in ('cloned', 'cloning')
                                and system_inhibit_0 != 'DELETED'
                                and volume.sum_wr_access - volume.sum_wr_err > 0 /*skip blanks*/
                                and library not like '%shelf%'
                           THEN label
                           ELSE NULL
                      END) as cloning_volumes,
       count(distinct CASE WHEN file_family like '%/_copy/_%' escape '/'  --match literal underscores
                                and system_inhibit_1 not in ('cloned',
                                                             'cloning')
                                and system_inhibit_0 != 'DELETED'
                                and volume.sum_wr_access - volume.sum_wr_err > 0 /*skip blanks*/
                                and library not like '%shelf%'
                           THEN label
                           ELSE NULL
                      END) as multiple_copy_volumes,
       count(distinct CASE WHEN library not like '%shelf%'
                             or system_inhibit_1 in ('migrated',
                                                     'migrating',
                                                     'duplicated',
                                                     'duplicating')
                           THEN label
                           ELSE NULL
                      END) as total,
       round(count(distinct CASE WHEN (/* Make sure that at least one
                                          destination has been scanned. */
                                       select count(*)
                                 from migration_history
                                 left join volume v2 on v2.id = migration_history.dst_vol_id
                                 where migration_history.src_vol_id = volume.id
                                   and migration_history.closed_time is not NULL
                                   /* Ingore recycled destination volumes. */
                                   and v2.system_inhibit_0 != 'DELETED') > 0
                                      and
                                      /* Reject if any destination volumes have
                                         not been scanned. */
                                      (select count(*)
                                 from migration_history
                                 left join volume v2 on v2.id = migration_history.dst_vol_id
                                 where migration_history.src_vol_id = volume.id
                                   and migration_history.closed_time is NULL
                                   /* Ingore recycled destination volumes. */
                                   and v2.system_inhibit_0 != 'DELETED') = 0

                                 THEN label
				 WHEN volume.sum_wr_access - volume.sum_wr_err = 0
				 THEN label  --Include blank tapes.
                                 ELSE NULL
                                 END)
                  / cast(count(distinct label) as DECIMAL(9,2)) * 100,2) as percentage_done
from volume
where (system_inhibit_0 != 'DELETED' 
       and label not like '%.deleted')
      and media_type != 'null'
      and capacity_bytes > 500  --Skip cleaning tapes.
group by media_type, capacity_bytes
order by capacity_bytes
) as inner_result
group by media_type
"
}




summary_skipped_bad_files()
{
psql -p $DB_PORT -h $DB_HOST -U $DB_USER $DB_NAME -c "
select /* It should be as simple as just using the media_type. However,
          LTO1 and LTO2 at FNAL are both set as 3480 do to limitations
          in the AML/2 when it was first put into use. */
       /*media_type,*/
       CASE WHEN media_type = '3480' and capacity_bytes = '107374182400'
            THEN 'LTO1'
            WHEN media_type = '3480' and capacity_bytes = '214748364800'
            THEN 'LTO2'
            WHEN media_type = '3480' and capacity_bytes < 100
            THEN NULL    --Cleaning tape; skip it.
            ELSE media_type
       END as media_type,
       system_inhibit_1 as migration_type,
       count(distinct src) as completed_volumes_with_skipped_bad_files,
       count(CASE WHEN migration.copied is NULL
                  THEN bad_file.bfid
                  ELSE NULL
             END) as bad_files
from volume
left join migration_history on migration_history.src_vol_id = volume.id
left join file on file.volume = volume.id
left join bad_file on bad_file.bfid = file.bfid
left join migration on bad_file.bfid = migration.src_bfid
where (system_inhibit_1 = 'migrated' or system_inhibit_1 = 'duplicated')
      and volume.label not like '%.deleted'
      and library not like '%shelf%'
      and media_type != 'null'
      and bad_file.bfid is not NULL
      and capacity_bytes > 500  --Skip cleaning tapes.
group by media_type,capacity_bytes,system_inhibit_1;
"
}



migration_per_day()
{
    volumes_per_day migrating migrated
}
duplication_per_day()
{
    volumes_per_day duplicating duplicated
}
cloning_per_day()
{
    volumes_per_day cloning cloned
}

#volumes_per_day()
#
#First argument is the in progress migration related state.  This list is one
#   of migrating, duplicating or cloning.
#Second argument is the copleted migration related state.  This lst is one
#   of migrated, duplicated or cloned.
volumes_per_day()
{
# Note: This sql command is similar to the daily plots and daily Duplicated
# table in the src/migration_summary_plotter_module.py and
# sbin/duplication_summary scripts, respectively.  Be sure to modify them
# when you modify this sql statement.
psql -p $DB_PORT -h $DB_HOST -U $DB_USER $DB_NAME -c "
/*This outer select just sorts the merged s1, s2 and s3 'day' columns into
  a unified sorted order. */
select * from
(
/* This inner select combines three sub selects sorted by day and
   media type. */
select CASE WHEN s1.day is not null THEN s1.day
            WHEN s2.day is not null THEN s2.day
            WHEN s3.day is not null THEN s3.day
            ELSE NULL
       END as day,
       CASE WHEN s1.media_type is not null THEN s1.media_type
            WHEN s2.media_type is not null THEN s2.media_type
            WHEN S3.media_type is not null THEN s3.media_type
            ELSE NULL
       END as media_type,
       CASE WHEN s2.started is not NULL THEN s2.started
            ELSE 0
       END as started,
       CASE WHEN s1.completed is not NULL THEN s1.completed
            ELSE 0
       END as completed,
       CASE WHEN s3.closed is not NULL THEN s3.closed
            ELSE 0
       END as closed
from

/*Three sub selects get the count for each day and media for number of
  volumes started, migrated/duplicated and closed. */

/****  s1  ****/
(
select date(time) as day,
       /* It should be as simple as just using the media_type. However,
          LTO1 and LTO2 at FNAL are both set as 3480 do to limitations
          in the AML/2 when it was first put into use. */
       /*media_type,*/
       CASE WHEN media_type = '3480' and capacity_bytes = '107374182400'
            THEN 'LTO1'
            WHEN media_type = '3480' and capacity_bytes = '214748364800'
            THEN 'LTO2'
            WHEN media_type = '3480' and capacity_bytes < 100
            THEN NULL    --Cleaning tape; skip it.
            ELSE media_type
       END as media_type,
       count(distinct CASE WHEN system_inhibit_1 in ('$2')
                            THEN label
                            ELSE NULL
                      END) as completed

from volume,migration_history
where volume.id = migration_history.src_vol_id
      /*and volume.library not like '%shelf%'*/
      and volume.media_type != 'null'
      and volume.system_inhibit_1 in ('$2')
      /* This time sub-query is needed to limit test volumes migrated
         multiple times to be counted only once. */
      and time = (select max(time)
                  from migration_history m2
                  where m2.src_vol_id = volume.id)
      and capacity_bytes > 500  --Skip cleaning tapes.
group by day,media_type,capacity_bytes
order by day,media_type
) as s1
/****  s1  ****/

/****  s2  ****/
full join (
select date(state.time) as day,
       /* It should be as simple as just using the media_type. However,
          LTO1 and LTO2 at FNAL are both set as 3480 do to limitations
          in the AML/2 when it was first put into use. */
       /*media_type,*/
       CASE WHEN media_type = '3480' and capacity_bytes = '107374182400'
            THEN 'LTO1'
            WHEN media_type = '3480' and capacity_bytes = '214748364800'
            THEN 'LTO2'
            WHEN media_type = '3480' and capacity_bytes < 100
            THEN NULL    --Cleaning tape; skip it.
            ELSE media_type
       END as media_type,
       count(distinct volume.label) as started
from volume,migration_history,state
where volume.id = migration_history.src_vol_id
      and volume.id = state.volume
      /*and volume.library not like '%shelf%'*/
      and volume.media_type != 'null'
      and volume.system_inhibit_1 in ('$1', '$2')
      /* Hopefully, setting state.time like this will correctly handle
         all vintages of the migration process.  The migrating and duplicating
         stages were added September of 2008. */
      and state.time = (select min(s5.time) from (
                        select CASE WHEN s2.value in ('$1')
                                    THEN min(s2.time)
                                    WHEN s2.value in ('readonly')
                                         and time > current_timestamp - interval '30 days'
                                    THEN min(s2.time)
                                    WHEN s2.value in ('$2')
                                    THEN min(s2.time)
                                    ELSE NULL
                               END as time
                        from state s2
                        where s2.volume = volume.id
                              and s2.value in ('$1', '$2',
                                               'readonly')
                        group by s2.value, time
                        order by s2.value, time
                        ) as s5)
      and capacity_bytes > 500  --Skip cleaning tapes.
group by day, volume.media_type,capacity_bytes
order by day, volume.media_type
) as s2 on (s1.day, s1.media_type) = (s2.day, s2.media_type)
/****  s2  ****/

/****  s3  ****/
full join (
select date(closed_time) as day,
       /* It should be as simple as just using the media_type. However,
          LTO1 and LTO2 at FNAL are both set as 3480 do to limitations
          in the AML/2 when it was first put into use. */
       /*media_type,*/
       CASE WHEN media_type = '3480' and capacity_bytes = '107374182400'
            THEN 'LTO1'
            WHEN media_type = '3480' and capacity_bytes = '214748364800'
            THEN 'LTO2'
            WHEN media_type = '3480' and capacity_bytes < 100
            THEN NULL    --Cleaning tape; skip it.
            ELSE media_type
       END as media_type,
       count(distinct label) as closed
from volume,migration_history
where volume.id = migration_history.src_vol_id
      /*and volume.library not like '%shelf%'*/
      and volume.media_type != 'null'
      and volume.system_inhibit_1 in ('$2')
      /* This time sub-query is needed to limit test volumes migrated
         multiple times to be counted only once. */
      and closed_time = (select max(closed_time)
                         from migration_history m2
                         where m2.src_vol_id = volume.id)
      and capacity_bytes > 500  --Skip cleaning tapes.
group by day,media_type,capacity_bytes
order by day,media_type
) as s3 on (s2.day, s2.media_type) = (s3.day, s3.media_type)
/****  s3  ****/

group by s1.day,s2.day,s3.day,s1.media_type,s1.completed,s2.media_type,s2.started,s3.media_type,s3.closed
order by s1.day,s2.day,s3.day
) as inner_result order by day;
"
}




volumes_remaining()
{
#This first query is just to obtain the list of media types that have
# at least one tape already migrated or duplicated.
media_types=`psql -p $DB_PORT -h $DB_HOST -U $DB_USER $DB_NAME -c "
select v2.media_type as src_media_type,
       v3.media_type as dst_media_type
from volume v2, migration_history, volume v3
where v2.id = migration_history.src_vol_id
  and v3.id = migration_history.dst_vol_id
  and v2.media_type != v3.media_type  --skip cloning
  and (v2.system_inhibit_1 = 'migrated'
       or v2.system_inhibit_1 = 'duplicated')
  and v2.system_inhibit_0 != 'DELETED'
  and v2.library not like '%shelf%'
  and v2.media_type != 'null'
  and v2.capacity_bytes > 500  --Skip cleaning tapes.
group by v2.media_type, v3.media_type
having count(v2.label) > 0;
" | sed '1,2d' | grep -v rows`
# | sed '/^$ */d'`  #Remove the first two header lines.

#Now we use that to build a list of comma seperated media_types.  We do
# this seperately for source and destination media_types.  Each comma 
# seperated item is enclosed in single quotes.
src_media_list=`echo "$media_types" | awk '{print $1}' | sort | uniq | sed -e "s/^/\'/" -e "s/ /\',\'/g" -e "s/$/\'/" | tr "\n" "," | sed 's/,$//'`
dst_media_list=`echo "$media_types" | awk '{print $3}' | sort | uniq | sed -e "s/^/\'/" -e "s/ /\',\'/g" -e "s/$/\'/" | tr "\n" "," | sed 's/,$//'`

psql -p $DB_PORT -h $DB_HOST -U $DB_USER $DB_NAME -c "
/* We need to use this function to convert a row of values into a single
   row string.  A temporary modifier or builtin function would be useful
   in this situation.  There should be a way to use CREATE FUNCTION
   to do this, but that syntax is more complicated. */
CREATE AGGREGATE rows2string(
  basetype  = text,
  sfunc     = textcat,
  stype     = text,
  initcond  = ''
);
" > /dev/null  #leave errors alone, just hide success messages.

echo "Source tapes not yet finished."
echo

psql -p $DB_PORT -h $DB_HOST -U $DB_USER $DB_NAME -c "
select /* It should be as simple as just using the media_type. However,
          LTO1 and LTO2 at FNAL are both set as 3480 do to limitations
          in the AML/2 when it was first put into use. */
       /*media_type,*/
       CASE WHEN volume.media_type = '3480' 
             and volume.capacity_bytes = '107374182400'
            THEN 'LTO1'
            WHEN volume.media_type = '3480'
             and volume.capacity_bytes = '214748364800'
            THEN 'LTO2'
            WHEN volume.media_type = '3480'
             and volume.capacity_bytes < 100
            THEN NULL    --Cleaning tape; skip it.
            ELSE volume.media_type
       END as media_type,
       volume.label,
       /* Report if the migration is in progress.  If it is done, then
          it is waiting on one or more destination tapes to be scanned. */
       CASE WHEN volume.system_inhibit_1 in ('migrated', 'migrating',
                                             'duplicated', 'duplicating',
                                             'cloned', 'cloning')
            THEN volume.system_inhibit_1
            ELSE NULL
       END as migration_state,
       /* Report all the tapes that have files migrated from this tape. */
       (select trim(' ' from rows2string(v3.label || ' '))
        from migration_history mh2
        left join volume v3 on mh2.dst_vol_id = v3.id
        where volume.id = mh2.src_vol_id
          and v3.system_inhibit_0 != 'DELETED') as migrated_to
from volume
where ( /* We obviously need to include un-migrated tapes in the robot. */
       (volume.system_inhibit_1 not in ('migrated', 'duplicated', 'cloned')
        and
        volume.library not like '%shelf%')
       or
       /* Include tapes still in progress (even if removed from the robot. */
       volume.system_inhibit_1 in ('migrating', 'duplicating')
       or
        (( /* Include migrated tapes without any entries in the 
              migration_history table. */
          (select count(*)
              from migration_history mh2
              left join volume v3 on mh2.dst_vol_id = v3.id
              where volume.id = mh2.src_vol_id
                and v3.system_inhibit_0 != 'DELETED') = 0
             and
              volume.system_inhibit_1 in ('migrated', 'duplicated', 'cloned'))
           or /* Include migrated tapes with missing closed_time entries
                 in the migration_history table. */
            ((select count(*)
              from migration_history mh2
              left join volume v3 on mh2.dst_vol_id = v3.id
               where volume.id = mh2.src_vol_id
                 and v3.system_inhibit_0 != 'DELETED'
                 and mh2.closed_time is NULL) > 0
             and
              volume.system_inhibit_1 in ('migrated', 'duplicated', 'cloned'))))
  and volume.system_inhibit_0 != 'DELETED'
  /* Source tapes should not contain multiple/duplicate copies.  For migration
     this is fine, but this could spell trouble for duplication when some
     file pairs have their primary and multiple copy statuses switched and
     remain out of sync with which tape has _copy_1 in the file_family. */
  and file_family not like '%/_copy/_%' escape '/'  --match literal underscores
  and volume.media_type != 'null'
  and volume.media_type in (${src_media_list})
  and volume.capacity_bytes > 500  --Skip cleaning tapes.
  and volume.sum_wr_access - volume.sum_wr_err > 0  --Skip blank tapes.
  and volume.wrapper != 'none' --Skip blank tapes recycled after write error
group by media_type,capacity_bytes,label,system_inhibit_1,volume.id
order by media_type,label;
"

#echo
#echo "Destination tapes not yet finished."
#echo

### Including the remaining tape information results in the script not
### completing in a reasonable time.  The problem section is needing to
### verify that there still exists a source-destination file pair
### for each volume pair listed in the migration_history table.  Leaving
### this clause out results in inaccurate output for tapes involved in
### restored original copies.

#Lets include the list destination tapes that need to be scanned.
#psql -p $DB_PORT -h $DB_HOST -U $DB_USER $DB_NAME -c "
#select /* It should be as simple as just using the media_type. However,
#          LTO1 and LTO2 at FNAL are both set as 3480 do to limitations
#          in the AML/2 when it was first put into use. */
#       /*media_type,*/
#       CASE WHEN media_type = '3480' and capacity_bytes = '107374182400'
#            THEN 'LTO1'
#            WHEN media_type = '3480' and capacity_bytes = '214748364800'
#            THEN 'LTO2'
#            WHEN media_type = '3480' and capacity_bytes < 100
#            THEN NULL    --Cleaning tape; skip it.
#            ELSE media_type
#       END as media_type,
#       label,
#       CASE WHEN system_inhibit_1 = 'none'
#            THEN 'not full'
#            WHEN system_inhibit_1 = 'readonly'
#            THEN 'not full (readonly)'
#            WHEN system_inhibit_1 = 'full'
#            THEN 'full'
#            ELSE NULL
#       END as fill_state,
#       /* Report if the scanning has started for this destination tape. */
#       /* Adding this column really slows down execution.  Commenting out
#          for now. */
#       /*CASE WHEN (select count(*)
#                  from migration, file
#                  where volume.id = file.volume
#                    and file.bfid = migration.dst_bfid
#                    and migration.checked is not NULL
#                  limit 1) > 0
#            THEN 'scanning'
#            ELSE NULL
#       END as scanning_state*/
#       /* Report all the tapes that have files migrated to this tape. */
#       (select trim(' ' from rows2string(v3.label || ' '))
#        from migration_history mh2
#        left join volume v3 on mh2.src_vol_id = v3.id
#        where volume.id = mh2.dst_vol_id) as migrated_from
#from volume
#where volume.system_inhibit_0 != 'DELETED'
#  and volume.media_type != 'null'
#  and volume.media_type in ('LTO4')  --(${dst_media_list})
#  and volume.capacity_bytes > 500  --Skip cleaning tapes.
#  and volume.sum_wr_access > 0  --Skip most blank tapes.
#  and volume.library not like '%shelf%'
#  /* If we fail the following condition the volume was not used in migration.
#     or duplication.  Need to use it to exclude multiple copy tapes, since
#     multiple copy and duplication destination tapes both have _copy_ in
#     the file_family. */
#  and (select count(src_vol_id)
#       from migration_history
#       left join volume v3 on v3.id = src_vol_id
#       where volume.id = dst_vol_id
#         and src_vol_id is not NULL
#         /* The src_vol_id and dst_vol_id columns in the migration_history
#             table were added later on.  Some 9940A to 9940B migrations
#             had dummy volume IDs inserted because they had been recycled
#             multiple times.  These dummy IDs were all negative integers.
#             We need to skip these. */
#         and src_vol_id > 0
#         and v3.sum_wr_access - v3.sum_wr_err > 0  --skip blank volumes
#         /* Skip counting cloned tapes.  They have their own page. */
#         and v3.system_inhibit_1 not in ('cloning', 'cloned')
#         and v3.label is not NULL  --skip old volumes without a record
#       limit 1) > 0
#  /* If there is a missing migration_history entry, include the tape
#     as work to be done. */
#  and (file_family like '%-MIGRATION%' or
#       file_family like '%/_copy/_%' escape '/' or  --match literal underscores
#       (select count(*)
#        from migration_history
#        left join volume v3 on v3.id = src_vol_id
#        where volume.id = dst_vol_id
#          and src_vol_id is not NULL
#          and closed_time is NULL
#          /* The src_vol_id and dst_vol_id columns in the migration_history
#             table were added later on.  Some 9940A to 9940B migrations
#             had dummy volume IDs inserted because they had been recycled
#             multiple times.  These dummy IDs were all negative integers.
#             We need to skip these. */
#          and src_vol_id > 0
#          and v3.sum_wr_access - v3.sum_wr_err > 0  --skip blank volumes
#          /* Skip counting cloned tapes.  They have their own page. */
#          and v3.system_inhibit_1 not in ('cloning', 'cloned')
#          and v3.label is not NULL  --skip old volumes without a record
#         /* Make sure at least one file still exists between the source
#            and destination volume pair.  Some migrations are restored that
#            result in the destination files simply being deleted.  This
#            leaves a record in the migration_history table that is not
#            closed and will never be closed.  These records need to be
#            ignored. */
#         and (select count(*)
#              from
#              (select *
#               from
#               (select f1.bfid
#                from file f1, volume v1
#                where f1.volume = v1.id
#                  and v1.id = v3.id) as source_files,
#               (select m2.src_bfid
#                from file f2, volume v2, migration m2
#                where f2.volume = volume.id
#                  and v2.id = f2.volume
#                  and f2.bfid = m2.dst_bfid) as destination_files
#               where source_files.bfid = destination_files.src_bfid
#              limit 1) as subquery) > 0
#          limit 1) > 0
#      )
#group by media_type,capacity_bytes,label,system_inhibit_1,volume.id
#order by media_type,label;
#"

psql -p $DB_PORT -h $DB_HOST -U $DB_USER $DB_NAME -c "
/* Lets not leave this lying around.  A temporary modifier would be useful
   in this situation. */
DROP AGGREGATE rows2string(text);
" > /dev/null  #leave errors alone, just hide success messages.


}




migration_history()
{
    history migrated
}
duplication_history()
{
    history duplicated
}
cloning_history()
{
    history cloned
}

#history()
#
#First argument is the in completed migration related state.  This list is one
#   of migrated, duplicated or cloned.
history()
{
psql -p $DB_PORT -h $DB_HOST -U $DB_USER $DB_NAME -c " \
select migration_history.src as src_volume,
       /* It should be as simple as just using the media_type. However,
          LTO1 and LTO2 at FNAL are both set as 3480 do to limitations
          in the AML/2 when it was first put into use. */
       /*volume.media_type,*/
       CASE WHEN volume.media_type = '3480' and volume.capacity_bytes = '107374182400'
            THEN 'LTO1'
            WHEN volume.media_type = '3480' and volume.capacity_bytes = '214748364800'
            THEN 'LTO2'
            WHEN volume.media_type = '3480' and volume.capacity_bytes < 100
            THEN NULL    --Cleaning tape; skip it.
            ELSE volume.media_type
       END as src_type,
       migration_history.dst as dst_volume,
       /* It should be as simple as just using the media_type. However,
          LTO1 and LTO2 at FNAL are both set as 3480 do to limitations
          in the AML/2 when it was first put into use. */
       /*v2.media_type,*/
       CASE WHEN v2.media_type = '3480' and v2.capacity_bytes = '107374182400'
            THEN 'LTO1'
            WHEN v2.media_type = '3480' and v2.capacity_bytes = '214748364800'
            THEN 'LTO2'
            WHEN v2.media_type = '3480' and v2.capacity_bytes < 100
            THEN NULL    --Cleaning tape; skip it.
            ELSE v2.media_type
       END as dst_type,
       volume.system_inhibit_1 as migration,
       time as time_completed
from migration_history
left join volume on volume.id = migration_history.src_vol_id
left join volume as v2 on v2.id = migration_history.dst_vol_id
where volume.system_inhibit_1 = '$1'
order by time;
"
}

make_html()
{
    title=$1
    temp_text_file=$2
    output_file=$3
    url_dir=$4

    temp_html_file=$temp_text_file.html

    #Remove the temporary file on failure.
    trap "rm -f $temp_html_file; exit 1" HUP INT QUIT ABRT ALRM TERM

    echo "Starting to making html file for \"$title\"."
    rm -f $output_file
    cat << EOF >> $temp_html_file
<html> <head> <title>$title</title> </head>
<body>
<body bgcolor="#ffffff" text=#000000">
<meta http-equiv="Refresh" content="900">
<pre>
EOF

    #We need to add a link to the web page with the plots on it.
    link="<a href=$url_dir/migration_summary/plot_enstore_system.html>Migration Summary Plots</a>"

    #The following sed is used more like cat to append $temp_text_file
    # to $output_file.html.  The fancy sed part just inserts the link
    # on line 3 in the process of "cat"ing the file.
    sed "3s;\(.*\);${link}\n\1;" $temp_text_file >> $temp_html_file

    echo >> $temp_html_file
    echo ${link} >> $temp_html_file
    echo >> $temp_html_file

    cat << EOF >> $temp_html_file
</pre>
</body>
EOF

    #Slide the new file into place.
    echo "Moving $temp_html_file to $output_file"
    mv $temp_html_file $output_file

    #Remove the temporary html file.
    rm -f $temp_html_file
}
