#! /bin/bash -e

prefix="@prefix@"
host=${1:-generic}
type=${2:-daily}
num=${3:-1}

HOST=$host
test -e "@sysconfdir@/backup.conf" && . "@sysconfdir@/backup.conf"

# warn if backup is n-times too old
warn=${4:-1}

# critical if backup is n-times too old
crit=${5:-3}

# backup period in days to check if backup timestamp is actual
case "$type" in
    (daily) period=${6:-1};;
    (weekly) period=${6:-7};;
    (monthly) period=${6:-31};;
    (*) period=${6:-0};;
esac

days=$((${num}*${period}))
dir=${TARGET:-/media/backup}/${host}-${type}.${num}
file=${dir}/backup-timestamp
name=${host}-${type}.${num}

if ps -fC backup-${host//./_} | grep -q ${type}; then
    running=" - backup is running"
    critstat="WARNING - "
    critret=1
else
    running=""
    critstat="CRITICAL - "
    critret=2
fi

if ! test -d ${dir}; then
    echo "${critstat}missing backup: ${name}${running}"
    exit $critret
fi

if ! test -f ${file}; then
    echo "${critstat}backup not complete: ${name}${running}"
    exit $critret
fi

age=$((($(date +"%s")-$(stat -c "%Z" ${file}))/3600/24))

if test ${age} -gt $((${days}*${crit})); then
    echo "${critstat}backup of ${name} too old, ${age} instead of ${days} days${running}"
    exit $critret
fi

if test ${age} -gt $((${days}*${warn})); then
    echo "WARNING - backup of ${name} too old, ${age} instead of ${days} days${running}"
    exit 1
fi

echo "OK - successful backup of ${name}${running}"
exit 0
