#! /bin/sh

# $Id$

#Dump the sparse volume list.  One list 0 to 10 percent and another 10 to
# 25 percent.

#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

#Create the variables that point to the files to output to.
fname=SPARSE_VOLUMES
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 be any time when the page is empty because the scipt is still writing
# the file.
rm -f $temp_file $old_output_file

active_sparse_volumes()
{
  sparse_volumes active $*
}

filled_sparse_volumes()
{
  sparse_volumes filled $*
}


#Define the function to obtain sparse volumes.
sparse_volumes()
{
  low_percentage=$3
  if [ -z "$low_percentage" ]; then
    low_percentage=0  #Make 0 low percentage default.
  fi
  high_percentage=$2
  if [ -z "$high_percentage" ]; then
    echo "No high percentage specified." 1>&2
    return 1
  fi

  #For the active and filled tables, assign the columns to be summed.
  if [ "$1" = "active" ]; then
     numerator=active_bytes
     denominator="active_bytes + deleted_bytes + unknown_bytes"

     #If active_files count equals zero, this volume is already on the
     # RECYCLABLE_VOLUMES page.
     skip_recyclable="and active_files > 0"
  else  #filled
     numerator="active_bytes + deleted_bytes + unknown_bytes"
     denominator=capacity_bytes

     skip_recyclable=""
  fi

  #Get the information to output.
  psql -p $DB_PORT -h $DB_HOST -U $DB_USER $DB_NAME -c "
  select label,library,storage_group,file_family,
         active_files,
         active_files + deleted_files + unknown_files as total_files,
         remaining_bytes,
         round((100.0 * active_bytes) /
               (active_bytes + deleted_bytes + unknown_bytes), 2)
               as \"active %\",
	 round((100.0 * (deleted_bytes + unknown_bytes)) /
               (active_bytes + deleted_bytes + unknown_bytes), 2)
               as \"non-active %\",
         round((100.0 * remaining_bytes) /
               (capacity_bytes), 2)
               as \"empty %\",
         round((100.0 * (capacity_bytes - remaining_bytes) /
               (capacity_bytes)), 2)
               as \"filled %\"
  from volume
  where library not like '%shelf%'  --skip removed tapes
    and system_inhibit_0 != 'DELETED'  --skip recycled/deleted tapes
    /* Skip tapes already migrated or being migrated. */
    and system_inhibit_1 not in ('migrated', 'migrating', 'duplicated',
                                 'duplicating', 'cloned', 'cloning')
    and file_family not like '%-MIGRATION%'
    and file_family not like '%/_copy/_%' escape '/'  --match literal underscores
    and (active_files + deleted_files + unknown_files) > 0  --skip blank tapes
    and (active_bytes + deleted_bytes + unknown_bytes) > 0  --skip zero bytes
    $skip_recyclable  --Don't show volumes on RECYCLABLE_VOLUMES page.
    and wrapper != 'null'
    and file_family != 'DELETED_FILES'
    and (system_inhibit_1 = 'full'
         or
         (system_inhibit_1 != 'full' and
          modification_time < current_timestamp - interval '3 months'))
    and $numerator < ($denominator) * ($high_percentage / 100.0)
    and $numerator >= ($denominator) * ($low_percentage / 100.0)
  group by library,storage_group,file_family,label,
           active_files,deleted_files,unknown_files,
           active_bytes,deleted_bytes,unknown_bytes,
           capacity_bytes,remaining_bytes
  order by storage_group,file_family,label;
  "
}

#Report the empty percentage of volumes per storage group.
empty_percentage()
{
  #Get the information to output.
  psql -p $DB_PORT -h $DB_HOST -U $DB_USER $DB_NAME -c "
  CREATE OR REPLACE FUNCTION filesize (in bytes float)
  RETURNS character varying AS E'
  DECLARE
     -- Declare a variable to hold the result.
    result CHARACTER VARYING;
     -- Declare a variable to hold running value.
    temp FLOAT = 0;
     -- These are used for determining the byte suffix.  (KiB, MiB, etc.)
    count INTEGER = 0;
    suffix CHARACTER VARYING DEFAULT \'B\';
  BEGIN
    temp = bytes;
    WHILE temp / 1024 > 1 LOOP
      temp := temp / 1024.0;
      count := count + 1;
    END LOOP;
    result := cast(temp as CHARACTER VARYING (5));
    IF ( count = 0 ) THEN
      result := result || \' B\';
    ELSIF ( count = 1 ) THEN
      result := result || \' KiB\';
    ELSIF ( count = 2 ) THEN
      result := result || \' MiB\';
    ELSIF ( count = 3 ) THEN
      result := result || \' GiB\';
    ELSIF ( count = 4 ) THEN
      result := result || \' TiB\';
    ELSIF ( count = 5 ) THEN
      result := result || \' PiB\';
    ELSIF ( count = 6 ) THEN
      result := result || \' EiB\';
    ELSIF ( count = 7 ) THEN
      result := result || \' ZiB\';
    ELSIF ( count = 8 ) THEN
      result := result || \' YiB\';
    END IF;
    RETURN result;
  END;
  ' LANGUAGE 'plpgsql';
  " > /dev/null

  psql -p $DB_PORT -h $DB_HOST -U $DB_USER $DB_NAME -c "
  select storage_group,
         count(volume) as volumes,
         filesize(sum(active_bytes)) as \"space active\",
         filesize(sum(remaining_bytes)) as \"space remaining\",
         filesize(sum(case when system_inhibit_1 not in  ('full', 'readonly')
                     then remaining_bytes
                     else 0
                  end)) as \"writable space remaining\",
         filesize(sum(active_bytes + deleted_bytes + unknown_bytes))
                  as \"space filled\",
         filesize(sum(capacity_bytes)) \"space allocated\",
         round((100.0 * sum(active_bytes)) /
               sum(active_bytes + deleted_bytes + unknown_bytes), 2)
               as \"active %\",
         round((100.0 * sum(deleted_bytes + unknown_bytes)) /
               sum(active_bytes + deleted_bytes + unknown_bytes), 2)
               as \"non-active %\",
         round((100.0 * sum(remaining_bytes)) /
               sum(capacity_bytes), 2) as \"empty %\",
         round((100.0 * sum(capacity_bytes - remaining_bytes)) /
               sum(capacity_bytes), 2) as \"filled %\"
  from volume
  where library not like '%shelf%'  --skip removed tapes
    and system_inhibit_0 != 'DELETED'  --skip recycled/deleted tapes
    /* Skip tapes already migrated or being migrated. */
    and system_inhibit_1 not in ('migrated', 'migrating', 'duplicated',
                                 'duplicating', 'cloned', 'cloning')
    and file_family not like '%-MIGRATION%'
    and file_family not like '%/_copy/_%' escape '/'  --match literal underscores
    and (active_files + deleted_files + unknown_files) > 0  --skip blank tapes
    and (active_bytes + deleted_bytes + unknown_bytes) > 0  --skip zero bytes
    and wrapper != 'null'  --skip null volumes
    and file_family != 'DELETED_FILES'  --skip known deleted file volumes
    --and system_inhibit_1 not in  ('full', 'readonly')  --only writable vols
  group by storage_group
  order by storage_group;
  "

  psql -p $DB_PORT -h $DB_HOST -U $DB_USER $DB_NAME -c "
  DROP FUNCTION filesize (float);
  " > /dev/null
}

#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

echo "Blank tapes not included in the following tables." >> $temp_file 2>&1
echo >> $temp_file 2>&1

echo                               >> $temp_file 2>&1
echo "===========================" >> $temp_file 2>&1
echo "Active Sparse Volumes < 10%" >> $temp_file 2>&1
echo "===========================" >> $temp_file 2>&1
echo                               >> $temp_file 2>&1

echo "Creating Active Sparse Volumes 10% List" `date`

#Report volumes between 0 and 10 percent full.
active_sparse_volumes 10 >> $temp_file 2>&1

echo                               >> $temp_file 2>&1
echo "===========================" >> $temp_file 2>&1
echo "Active Sparse Volumes < 25%" >> $temp_file 2>&1
echo "===========================" >> $temp_file 2>&1
echo                               >> $temp_file 2>&1

echo "Creating Active Sparse Volumes 25% List" `date`

#Report volumes between 10 and 25 percent full.
active_sparse_volumes 25 10 >> $temp_file 2>&1

echo                               >> $temp_file 2>&1
echo "===========================" >> $temp_file 2>&1
echo "Filled Sparse Volumes < 10%" >> $temp_file 2>&1
echo "===========================" >> $temp_file 2>&1
echo                               >> $temp_file 2>&1

echo "Creating Filled Sparse Volumes 10% List" `date`

#Report volumes between 0 and 10 percent full.
filled_sparse_volumes 10 >> $temp_file 2>&1

echo                               >> $temp_file 2>&1
echo "===========================" >> $temp_file 2>&1
echo "Filled Sparse Volumes < 25%" >> $temp_file 2>&1
echo "===========================" >> $temp_file 2>&1
echo                               >> $temp_file 2>&1

echo "Creating Filled Sparse Volumes 25% List" `date`

#Report volumes between 10 and 25 percent full.
filled_sparse_volumes 25 10 >> $temp_file 2>&1

echo                                             >> $temp_file 2>&1
echo "=========================================" >> $temp_file 2>&1
echo "Volume Empty Percentage per Storage Group" >> $temp_file 2>&1
echo "=========================================" >> $temp_file 2>&1
echo                                             >> $temp_file 2>&1

echo "Creating Volume Empty Percentage per Storage Group" `date`

#Report empty percentage per storage group.
empty_percentage >> $temp_file 2>&1

#Turn out the html page.
make_html "$tl_name Sparse Volumes Page" $temp_file $output_file $url_dir

#Remove the temp file.
rm -f $temp_file
