#!/usr/bin/env bash
# File: /usr/lib/nagios/plugins/check_justconnect_backup
#    0 - all ok
#    1 - warning
#    2 - critical
#    3 - unknown 

# Check if properties file has been specified
checkPropertiesFile() {
    if [ ! -s "$1" ]; then
      echo "OK - backup.properties does not exist"
      exit 0
    fi
    if [ -z "$1" ]
    then
        echo "No backup.properties file given."
  	exit 3
    fi
    # read the properties
    . $1
}


# Reads the timestamp from the backup.status.log file
getBackupStatusTimeStamp() {
    cat $backup_status_log_file | sed -e 's/^\[.*\] \(.*\)$/\1/g'
}

# 0 = OK
# 1 = WARNING
# 2 = NOT_FINISHED
# 2 = NOT_STARTED
# 2 = ERROR 
getBackupStatus() {
    result=0
    backup_status_log_file=$1
    if grep -q '#.*/bin/backup-cron.sh' /etc/cron.d/just-backup; then
        echo "Backup ist deaktiviert"
        exit 0
    fi
    if [ ! -e $backup_status_log_file ]; then
	echo "Backup status log file does not exist"
	exit 3
    else
        log_size=`cat $backup_status_log_file | wc -l`
        if [ $log_size -eq 0 ]; then
            status=$(zcat $backup_status_log_file".1.gz" | sed -e 's/^\[\(.*\)\].*/\1/g')
        else
            status=$(cat $backup_status_log_file | sed -e 's/^\[\(.*\)\].*/\1/g')
        fi
	case "$status" in
	    'STARTED')
		backup_started_at=$(getBackupStatusTimeStamp)
                # Check the time spent for backup
		time_spent=$(expr $(date '+%s') - $(date -d "$backup_started_at" '+%s'))
                # Backup took more then 3 hours => error
		if [ $time_spent -gt $BACKUP_DURATION_TIME_IN_SECONDS ]; then
		    echo "Backup took too long. It took longer than $BACKUP_DURATION_TIME_IN_SECONDS seconds"
		    exit 2
		fi
		;;
	    'FINISHED')
		backup_finished_at=$(getBackupStatusTimeStamp)
                # Check the time the last backup ran
		time=$(expr $(date '+%s') - $(date -d "$backup_finished_at" '+%s'))
		
                # Last backup ran more than 25 hours ago=> error
		if [ $time -gt $BACKUP_INTERVAL_TIME_IN_SECONDS ]; then
		    echo "Backup was not started within the last $BACKUP_INTERVAL_TIME_IN_SECONDS seconds"
		    exit 2
		fi	        
		;;
	    'WARN')
		echo "Backup returned a warning. Please look at log file $BACKUP_ERROR_LOG_FILE and $BACKUP_ERROR_LOG_FILE"
		exit 1
		;;
	    'ERROR')
		echo "Backup returned an error. Please look at log file $BACKUP_ERROR_LOG_FILE and $BACKUP_LOG_FILE"
		exit 2
		;;	    
	esac
    fi
	    
    echo  "Backup is ok"
    exit 0

}


checkPropertiesFile $1
getBackupStatus $BACKUP_STATUS_LOG_FILE
