#!/bin/sh
set -u  # force better programming and ability to use check for not set
if [ "${1:-}" = "-x" ] ; then set -xv; shift; fi

timeout='--timeout 10 --retries 3'
#Override the default time allowed to wait for the mover.  This is used as
# a workaround for cases where it takes longer than 15 minutes for a tape
# to be mounted.
mover_timeout='--mover-timeout 1800'  #30 minutes (defualt is 15 minutes)

if [ -n "${1:-}" ];then
  FULL=`echo $1 | tr a-z A-Z `
else
  FULL="NO"
fi

node=`uname -n| sed -e 's/\([^\.]\)\..*/\1/'`

# function to return date so it can be used in filename
date_string() { date +"%Y-%m-%d.%H.%M" ; }

# function to return date so it can be used in directory path
date_string_d() { date +"%Y/%m/%d/%H" ; }

today=`date +"%Y-%m-%d"`
now=`date +"%s"`

list() { echo "$1"
         if [ "${BACKUP_LOG:-}" != "" ]; then echo "$1" >>$BACKUP_LOG; fi
       }

#function to list command, execute it and list status
doit() { list "$1"
         doutput=/tmp/doit_output
         rm -f $doutput
         eval "nice -n 20 $1" >>$doutput 2>&1
         status=$?
         if [ `echo $1 | grep -c encp` -ne 0 -a `grep -c STATUS=ok $doutput` -eq 0 ]; then status=1; fi
         cat $doutput
         if [ "${BACKUP_LOG:-}" != "" ]; then cat $doutput >>$BACKUP_LOG; fi
         list "Status= $status"
         list ""
         if [ $status -ne 0 ]; then touch $QUIT; exit $status ;fi
       }

#Tapes have to be declared to the volume server and in the correct storage
# family
saveit() {
           pnfsname=`echo $1 | tr '/' '-' | sed s/-//`
           ls -l $1
           doit "encp $mover_timeout --data $verbose $1 $pnfspath/$pnfsname"
           status=$?
           ls -l $pnfspath/$pnfsname
           if [ $status -ne 0 ]; then touch $QUIT; exit $status; fi
         }

#This is the directory that this script finds where the backups are stored.
backup_path=`enstore config $timeout --show backup dir`
if [ $? -ne 0 ]; then
   echo "No backup dir specified in configuration.  Aborting."
   exit 1
fi
if [ ! -d "$backup_path" ]; then
   echo "Backup directory $backup_path does not exist.  Aborting."
   exit 1
fi
#This is the directory in PNFS that the backups are written into.
pnfspath=`enstore config $timeout --show crons backup2tape_dir`
if [ $? -ne 0 ]; then
   echo "No backup2tape dir specified in configuration.  Aborting."
   exit 1
fi
pnfspath=$pnfspath/`date_string_d` #Append the current date.
# try to make a unique directory pathname, but give up after 10 tries
x=0
while [ $x -le 10 -a -d $pnfspath ]; do
   x=`expr $x + 1`
   pnfspath=${pnfspath}.next
done
# Now test if the directory is good to go.
if [ ! -d "$pnfspath" ]; then
   mkdir -p "$pnfspath"   #Actually attempt to make the directory.
   if [ $? -ne 0 ]; then
     echo "Unable to make $pnfspath directory.  Aborting."
     exit 1
   fi
elif [ -d $pnfspath ]; then
   list "$pnfspath exists, quitting"
   exit 1
fi
export pnfspath
#This is the config host for the Enstore system we plan to use.  By
# default use default ENSTORE_CONFIG_HOST value.
config_host=`enstore config $timeout --show crons backup2tape_config_host 2> /dev/null`
if [ $? -eq 0 ]; then
   ENSTORE_CONFIG_HOST=$config_host
fi
#This is the config host for the Enstore system we plan to use.  By
# default use default ENSTORE_CONFIG_HOST value.
config_port=`enstore config $timeout --show crons backup2tape_config_port 2> /dev/null`
if [ $? -eq 0 ]; then
   ENSTORE_CONFIG_PORT=$config_port
fi

verbose="--verbose=1"
filePath=`dirname $backup_path` #All backup files are under this directory.
VAULT=${filePath}/BackupToTape
if [ ! -d $VAULT ]; then mkdir $VAULT; fi
BACKUP_LOG=${VAULT}/backup_log;     export BACKUP_LOG
PNFS=`find ${filePath} -name "pnfs-backup*" | grep -v xlogs` #strip xlogs
ENSTORE=${filePath}/enstore-backup
ENSTORELOG=${filePath}/enstore-log-backup
QUIT=$VAULT/QUIT
TIMEONDISK=1  #days


rm -f $BACKUP_LOG
rm -f $VAULT/*.tbz2 #old junk
rm -f $QUIT

############################################################################
# decided if we need to do a full backup or incremetal since last full backup

START_BACKUP_DATE=$VAULT/start_backup_date
rm -f $START_BACKUP_DATE
touch $START_BACKUP_DATE  #make this now, mv'ing it later will NOT change the access time

LAST_BACKUP_DATE=$VAULT/last_backup_date
list "Last backup on `ls -l $LAST_BACKUP_DATE`"

if [ $FULL = "FULL" ]; then
   find_options="-follow"
   kind=FULL
else
   find_options="-follow -newer $LAST_BACKUP_DATE"
   kind=INCREMENTAL
fi


#### PNFS Database Backup ##################################################
# copy the files that have not been copied to tape

PNFS_FILES=$VAULT/pnfs.files
rm -f $PNFS_FILES
touch $PNFS_FILES
# Here we create the xlogs tar files and put them in the corresponding
# pnfs-backup directories.
for xd in $PNFS
do
        fn=`find ${xd}.xlogs $find_options -type f -name '*backup.Z' | sort | head -n1`
        if [[ $fn != "" ]]
        then
	  # extract name of the tarfile w/o 'tar.Z' suffix
	  # FIXME: this relies on a name not having dots, revisit later
          tarfile=`zcat ${fn} | fgrep LABEL |  awk '{ print $NF }' | xargs basename  | cut -f1,2 -d .`
	  # find starting WAL file
	  startwal=`zcat ${fn} | fgrep 'START WAL' | cut -f6 -d' ' | cut -f1 -d')'`.Z
	  startwal=${xd}.xlogs/$startwal
          fl=`find ${xd}.xlogs -follow -type f -newer $startwal`
          if [[ $fl != "" ]]
          then
            tar cfz ${xd}/xlogs-${tarfile}.tar.Z $startwal $fl
            find ${xd}  -maxdepth 1  -name "*${tarfile}*Z"  >> $PNFS_FILES
          fi
        fi
done
lines=`wc -l $PNFS_FILES | awk '{print $1}'`
list ""
list "PNFS databases backup: $lines files to backup to tape"
doit "cat $PNFS_FILES"
cat $PNFS_FILES | while read f ; do ls -l $f; done
list ""
counter=0
cat $PNFS_FILES| while read file; do
  counter=`expr $counter + 1`;
  list "$counter of $lines PNFS database files: $file"
  saveit $file
done
if [ -f $QUIT ]; then exit 1; fi
rm -f $PNFS_FILES
find $PNFS -type f -follow -daystart -mtime +$TIMEONDISK -exec rm -fr {} \;


#### Enstore Database Backup ###############################################
# copy the files that have not been copied to tape

ENSTORE_FILES=$VAULT/enstore.files
rm -f $ENSTORE_FILES
#only backup the latest directory copy.
ELAST=`ls -ltd  $ENSTORE/dbase.* | head -n1 | awk '{print $NF}'`
find $ELAST -type f $find_options -print > $ENSTORE_FILES
# tar journal files
# make a list of journal files
find $ENSTORE/JOURNALS -type f $find_options -print > /tmp/journals
# file list without path
for i in `cat /tmp/journals`; do basename $i; done > /tmp/journal_files
# do tar-ing in $ENSTORE/JOURNALS
if [ -s /tmp/journal_files ]
then
	(cd $ENSTORE/JOURNALS; tar cvf journals.tar `cat /tmp/journal_files`)
	echo $ENSTORE/JOURNALS/journals.tar >> /tmp/journals
	echo $ENSTORE/JOURNALS/journals.tar >> $ENSTORE_FILES
fi
rm -f /tmp/journal_files
# cat /tmp/journals >> $ENSTORE_FILES
ls $backup_path/ACC-DST/* >> $ENSTORE_FILES

lines=`wc -l $ENSTORE_FILES | awk '{print $1}'`
list ""
list "ENSTORE databases backup: $lines files to backup to tape"
doit "cat $ENSTORE_FILES"
list ""
counter=0
cat $ENSTORE_FILES| while read file; do
  counter=`expr $counter + 1`;
  list "$counter of $lines ENSTORE database files: $file"
  saveit $file
done
if [ -f $QUIT ]; then exit 1; fi
rm -f $ENSTORE_FILES
# rm backup journals
for i in `cat /tmp/journals`
do
  rm -f $i
done
rm -f /tmp/journals
find $ENSTORE -follow -daystart -mtime +$TIMEONDISK -exec rm -fr {} \;




#### Enstore Log Backup ####################################################
# bzip2/copy the files that have not been copied, excluding today's, to tape

ENSTORELOG_FILES=$VAULT/enstorelog.files
rm -f $ENSTORELOG_FILES
find $ENSTORELOG -type f $find_options  -name "LOG*"  | grep -v "$today" > $ENSTORELOG_FILES
lines=`wc -l $ENSTORELOG_FILES | awk '{print $1}'`
list ""
list "ENSTORE log backup: $lines files to backup to tape"
doit "cat $ENSTORELOG_FILES"
list ""
counter=0
cat $ENSTORELOG_FILES| while read file; do
  counter=`expr $counter + 1`;
  list "$counter of $lines ENSTORE log files: $file"
  output=$VAULT/`basename $file`.$now.tbz2
  doit "bzip2 < $file > $output"
  saveit $output
  rm -f $output
done
if [ -f $QUIT ]; then exit 1; fi
rm -f $ENSTORELOG_FILES
find $ENSTORELOG -follow -daystart -mtime +30 -exec rm -fr {} \;
find $ENSTORELOG -follow -daystart -name "DEBUGLOG*" -mtime +10 -exec rm -fr {} \;


#### Billing DB backup ####################################################

BILLING_FILES=$VAULT/billing.files
rm -f $BILLING_FILES
if [ ! -d ${filePath}/billing-backup ]; then
    mkdir  ${filePath}/billing-backup
fi
find ${filePath}/billing-backup -type f $find_options  -name "*sql*"  > $BILLING_FILES
lines=`wc -l $BILLING_FILES | awk '{print $1}'`
list ""
list "Billing backup: $lines files to backup to tape"
doit "cat $BILLING_FILES"
list ""
counter=0
cat $BILLING_FILES| while read file; do
  counter=`expr $counter + 1`;
  list "$counter of $lines billing files: $file"
  saveit $file
done
if [ -f $QUIT ]; then exit 1; fi
rm -f $BILLING_FILES
find ${filePath}/billing-backup -type f $find_options  -name "*sql*" -exec rm -fr {} \;

############################################################################

#next time, get only new files since we started the backup.
mv $START_BACKUP_DATE $LAST_BACKUP_DATE

#  send mail to let people know what was backed up
cat $BACKUP_LOG | /usr/bin/Mail -s "Metadata tape backup OK. Log from $node on `uname -n`" $ENSTORE_MAIL

list "`date`: Finished backup on $node"

exit 0
