
#!/bin/sh
# File	: copy-clean_dfm-db_backup.sh
# By	: Maarten.deBoer@Atos.net, 120105
# Subject	: Copy & Clean (remove) DFM-DB-backup-data via NFS-mount to filer
#Mod(0.3)	: rm 2 old files added
#set -x
PGM="`basename $0|cut -d\. -f1`"
VER="0.3"
TMP="/tmp/${PGM}.$$"
LOG="${HOME}/log/${PGM}.log"
HOSTNAME="`hostname|cut -d\. -f1`"
MAILTO="maarten.deboer@atos.net"
DFMDBBACKUPDIR="/appl/dfm/data/backup/"
DESTBACKUPDIR="/appl/dfm/backup/${HOSTNAME}/"
MAXPERC=60

echo "`date` ${PGM} (v${VER}) started." | tee -a ${LOG}
touch ${TMP}

PROC="`ps -ef|grep -v grep|grep 'dfm backup'`"

if [ "$PROC" = "" ]; then
# No DFM backup is running. So copy can be done
  echo "Getting list from ${DESTBACKUPDIR} ..."

# List backup-files at dest.
  ls -1 ${DESTBACKUPDIR}*.ndb > ${TMP}

  cd ${DFMDBBACKUPDIR}
  ls -1 *.ndb | while read SRCFILE
  do
    grep ${SRCFILE} ${TMP}
    EC=$?
    if [ ${EC} -eq 0 ]; then
    # File found
      echo "${SRCFILE} found."
    else
      echo "${SRCFILE} NOT found. Copy needed."
      cp ${SRCFILE} ${DESTBACKUPDIR}
      EC=$?
      echo "`date` ${PGM} copied (${EC})."|tee -a ${LOG}
    fi
  done
# cleanup
  PERCUSED="`df -m ${DESTBACKUPDIR} |grep -v Used| awk '{print $4}'|sed 's/%//g'`"
  echo "`date` ${PERCUSED}% used space at ${DESTBACKUPDIR}"|tee -a ${LOG}
  if [ ${PERCUSED} -gt ${MAXPERC} ]; then
    echo "  Cleaning (>${MAXPERC}%) needed." |tee -a ${LOG}
    cat ${TMP}
    COUNT="`wc -l ${TMP}|cut -d' ' -f1`"
    if [ ${COUNT} -gt 5 ]; then
# If more then 3 files one(1) , oldest, maybe removed
      OLDEST="`head -2 ${TMP}`"
      echo "  The oldest 2 files (${OLDEST}), of ${COUNT}, will be removed ..."|tee -a ${LOG}
##ls -l ${OLDEST}
      rm ${OLDEST}
      EC=$?
      echo "Remove of ${OLDEST} with ExitCode=${EC}"|tee -a ${LOG}
    fi
  fi

else
  echo "`date` ${PGM} DFM-backup (${PROC})is still running. So NO copy will be done."|tee -a ${LOG}
fi


rm ${TMP}
echo "`date` ${PGM} finished." | tee -a ${LOG}
exit 0

