#!/bin/bash
#
##################################################
#
# Global Variables
#
##################################################
SCRIPT_NAME=`basename $0`
BACKUP_TOOL=/bin/tar
DIRS="/usr/local/nagios"
BACKUP_PATH=/backup/
EMAIL=humus@yyy.com
LOG_DIR=/var/backup_log/${SCRIPT_NAME}
LOG_FILE=${LOG_DIR}/${SCRIPT_NAME}.log
DAY_OF_MONTH=`date +%d`
##################################################
#
# Functions
#
##################################################
function validation
{
        # check that log dir exist
        if [ ! -d ${LOG_DIR} ]
        then
                mkdir -p ${LOG_DIR}
                err_handle $? "mkdir -p ${LOG_DIR}"
        fi
        # check that backup dir exist
        if [ ! -d ${BACKUP_PATH} ]
        then
                write_log "Error: backup dir ${BACKUP_PATH} does not exist!"
                exit 1
        fi
        # check that day of the month directory exist under backup directory
        if [ ! -d ${BACKUP_PATH}/${DAY_OF_MONTH} ]
        then
                mkdir -p ${BACKUP_PATH}/${DAY_OF_MONTH}
                err_handle $? "mkdir -p ${BACKUP_PATH}/${DAY_OF_MONTH}"
        fi
}
##################################################
function write_log
{
        echo "`date +%F_%T` $*" >> ${LOG_FILE}
}
##################################################
function err_handle
{
        ERR=$1
        COMMAND=$2
        if [ ${ERR} = 0 ]
        then
                write_log "command ${COMMAND} completed successfully"
        else
                write_log "Error: command ${COMMAND} failed with error code=${ERR}"
                cat ${LOG_FILE} | mail -s "${SCRIPT_NAME} script on `hostname` failed!" ${EMAIL}
                exit 2
        fi
}
##################################################
function backup_dir
{
        DIR_NAME=$1
        BACKUP_DIR=$2

        write_log "start backup ${DIR_NAME} repository"
        ${BACKUP_TOOL} -zcf ${BACKUP_DIR} ${DIR_NAME} > /dev/null 2>&1
        err_handle $? "${BACKUP_TOOL} -zcf ${BACKUP_DIR} ${DIR_NAME}"
        write_log "finish backup ${DIR_NAME} repository"
}
##################################################
#
# Main
#
##################################################
validation
write_log "------------- Start backup script -----------------------"
for DIR in ${DIRS}
do
        backup_dir "${DIR}" "${BACKUP_PATH}/${DAY_OF_MONTH}/`basename ${DIR}`.tar.gz"
done
write_log "-------------- Finish backup script ----------------------"