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

# bin/$RCSfile: backup2Tape,v $  $Revision: 1.44 $


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 +"%b %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
       }

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

verbose="--verbose=1"

# filePath='/diska'
# VAULT=${filePath}/BackupToTape
# BACKUP_LOG=${VAULT}/backup_log;     export BACKUP_LOG
# PNFS=${filePath}/pnfs-backup*/
# ENSTORE=${filePath}/enstore-backup
# ENSTORELOG=${filePath}/enstore-log-backup
# QUIT=$VAULT/QUIT
# TIMEONDISK=1  #days

backup_path=`enstore config --show backup| grep "'dir':" | cut -d"'" -f 4`
filePath=`dirname $backup_path`
VAULT=${filePath}/BackupToTape
if [ ! -d $VAULT ]; then mkdir $VAULT; fi
BACKUP_LOG=${VAULT}/backup_log;     export BACKUP_LOG
PNFS=${filePath}/pnfs-backup*/
ENSTORE=${filePath}/enstore-backup
ENSTORELOG=${filePath}/enstore-log-backup
QUIT=$VAULT/QUIT
TIMEONDISK=1  #days

## Fermi specific stuff
#if [ $node = d0ensrv3 ]; then
#  pnfspath="/pnfs/eagle/d0en-backups/`date_string_d`"; export pnfspath
#  ENSTORE_CONFIG_HOST=stkensrv2.fnal.gov
#
#elif [ $node = d0ensrv3n ]; then
#  pnfspath="/pnfs/eagle/d0en-backups/`date_string_d`"; export pnfspath
#  ENSTORE_CONFIG_HOST=stkensrv2.fnal.gov
#
#elif [ $node = stkensrv3 ]; then
#  pnfspath="/pnfs/eagle/backups/`date_string_d`"; export pnfspath
#
#elif [ $node = cdfensrv3 ]; then
#  pnfspath="/pnfs/eagle/cdfen-backups/`date_string_d`"; export pnfspath
#  ENSTORE_CONFIG_HOST=stkensrv2.fnal.gov
#
#elif [ $node = gccensrv2 ]; then
#  pnfspath="/pnfs/eagle/gccen-backups/`date_string_d`"; export pnfspath
#  ENSTORE_CONFIG_HOST=stkensrv2.fnal.gov
#
#else
#  doit "echo Do not know about node $node... fix $ENSTORE_DIR/sbin/backup2Tape script"
#  exit 1
#fi

case "$node" in
	d0en*)
		pnfspath="/pnfs/eagle/d0en-backups/`date_string_d`"; export pnfspath
		ENSTORE_CONFIG_HOST=stkensrv2.fnal.gov
		;;
	stken*)
		pnfspath="/pnfs/eagle/backups/`date_string_d`"; export pnfspath
		;;
	cdfen*)
		pnfspath="/pnfs/eagle/cdfen-backups/`date_string_d`"; export pnfspath
		ENSTORE_CONFIG_HOST=stkensrv2.fnal.gov
		;;
	gccen*)
		pnfspath="/pnfs/eagle/gccen-backups/`date_string_d`"; export pnfspath
		ENSTORE_CONFIG_HOST=stkensrv2.fnal.gov
		;;
	*)
		doit "echo Do not know about node $node... fix $ENSTORE_DIR/sbin/backup2Tape script"
		exit 1
		;;
esac

rm -f $BACKUP_LOG

# try to make a unique directory, but give up after 10 tries
x=0; while [ $x -le 10 -a -d $pnfspath ]; do x=`expr $x + 1`; pnfspath=${pnfspath}.next; done
if [ -d $pnfspath ]; then list "$pnfspath exists, quitting"; fi
mkdir -p $pnfspath

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
###VP 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`
#        echo Backup file=${fn}
        if [[ $fn != "" ]]
        then
          tarfile=`zcat ${fn} | fgrep LABEL | cut -f8 -d/ | cut -f1,2 -d .`
#          echo Tar file=\"$tarfile\"
	  startwal=`zcat ${fn} | fgrep 'START WAL' | cut -f6 -d' ' | cut -f1 -d')'`.Z
	  startwal=${xd}xlogs/$startwal
#	  echo Start WAL=\"$startwal\"
          fl=`find ${xd}xlogs -follow -type f -newer $startwal`
          if [[ $fl != "" ]]
          then
            tar cfz ${xd}xlogs-${tarfile}.tar.Z $startwal $fl
          fi
        fi
done
###VP
#only backup latest copy on disk, not all of them since we are running out of tape!
find $PNFS $find_options -maxdepth 1 -type f  -print | sort -r | while read f; do
    echo $f | cut -f1 -d.
  done | uniq | while read g; do 
    ls -lt ${g}.*.Z | head -n1 | awk '{print $NF}'
  done > $PNFS_FILES

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/*.01 >> $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*"  -exec ls -l {} \; | grep -v "$today" | awk '{print $NF }' > $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 {} \;


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

#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
