#!/bin/bash

PROGNAME=${0##*/}

function nagios_exit_usage() {
    echo "\
Usage: $PROGNAME [OPTION...] -e entity
Nagios plugin to check for (z)RANCiD backup freshness

Options:
  -e, --entity NAME                 Entity name
  -w, --warning SECONDS             Warning threshold in seconds
  -c, --critical SECONDS            Critical threshold in seconds
  -s, --min-size BYTES              File size in bytes
  -mod, --max-output-detail NUM     Add error devices to output
  -u, --url                         Get data via HTTP api
  -t, --timeout                     Timeout when --url is used
  -h, --help                        Display this help
"
    exit 3
}

STATUS_PRIO=( 0 1 3 2 )
STATUS_TEXT=( OK WARNING CRITICAL UNKNOWN )

# $1: current status
# $2: other_status
# $REPLY: new value for current status
function worsen_status() {
    local current=$1; shift
    local other=$1; shift
    if (( STATUS_PRIO[other] > STATUS_PRIO[current] )); then
        REPLY=$other
    else
        REPLY=$current
    fi
}

entity=
declare -A perf=(
    [fresh]=0
    [too_old]=0
    [too_small]=0
    [disabled]=0
)
declare -A warn=()
declare -A crit=()
max_output_detail=0
url=
timeout=5

while (( $# > 0 )); do
    case "$1" in
        -e|--entity) entity=$2; shift ;;
        -w|--warning) warn[too_old]=$2; shift ;;
        -c|--critical) crit[too_old]=$2; shift ;;
        -s|--min-size) crit[too_small]=$2; shift ;;
        -mod|--max-output-detail) max_output_detail=$2; shift ;;
        -u|--url) url=$2; shift ;;
        -t|--timeout) timeout=$2; shift ;;
        *) nagios_exit_usage ;;
    esac
    shift
done

[[ -z $entity ]] && nagios_exit_usage
for i in "${warn[@]}" "${crit[@]}"; do [[ -n ${i//[0-9]} ]] && nagios_exit_usage; done
[[ -n ${max_output_detail//[0-9]} ]] && nagios_exit_usage
[[ -n ${timeout//[0-9]} ]] && nagios_exit_usage

if [[ -n $url ]]; then
    [[ $url == *\?* ]] && url+='&' || url+='?'
    url+='verbose=3'
fi

now=$(date +%s)
state=0
long_output=()
declare -A output_detail=(
    [too_old]=
    [too_small]=
)

# $1: key
# $2: total key count
# $3: device to add to verbose output
function add_output_detail() {
    (( $2 > max_output_detail )) && return
    (( $2 == max_output_detail )) && { output_detail[$1]+=', ...'; return; }
    output_detail[$1]+="${output_detail[$1]:+, }${3%.*}"
}

ignore_re='\<alert=0\>'
while read -r device last size type updown comment; do
    if [[ $device == \#pipestatus:* ]]; then
        if (( ${device##*:} != 0 )); then
            echo 'UNKNOWN: Failed to get data'
            exit 3
        fi
        break
    fi

    if [[ $updown != up ]]; then
        (( perf[disabled]+=1 ))
        continue
    fi
    if [[ $comment =~ $ignore_re ]]; then
        (( perf[disabled]+=1 ))
        continue
    fi

    fresh=1
    if [[ -n ${crit[too_old]} ]] && (( now - last > crit[too_old] )); then
        worsen_status "$state" "2"; state=$REPLY
        add_output_detail too_old "${perf[too_old]}" "$device"
        (( perf[too_old]++, fresh=0 ))
        long_output+=( "$device: too old (crit)" )
    elif [[ -n ${warn[too_old]} ]] && (( now - last > warn[too_old] )); then
        worsen_status "$state" "1"; state=$REPLY
        add_output_detail too_old "${perf[too_old]}" "$device"
        (( perf[too_old]++, fresh=0 ))
        long_output+=( "$device: too old (warn)" )
    fi
    if [[ -n ${crit[too_small]} ]] && (( size < crit[too_small] )); then
        worsen_status "$state" "2"; state=$REPLY
        add_output_detail too_small "${perf[too_small]}" "$device"
        (( perf[too_small]++, fresh=0 ))
        long_output+=( "$device: too small (crit)" )
    fi
    (( perf[fresh]+=fresh ))

done < <(
    # avoid temporary file, here-string included
    if [[ -z $url ]]; then
        zrancid-ls -e "$entity" -vvv
    else
        curl -kfsS -m "$timeout" --get --data-urlencode "entity=$entity" "$url"
    fi
    echo "#pipestatus:$?"
)

output=
perfdata=
for k in "${!perf[@]}"; do
    [[ (-n ${warn[$k]} || -n ${crit[$k]}) && ${perf[$k]} != 0 ]] && e='**' || e=
    current="${e}${k}=${perf[$k]}${e}"
    (( max_output_detail > 0 )) && current+="${output_detail[$k]:+ (${output_detail[$k]})}"
    [[ -n $e ]] && output="${current}${output:+, }${output}" || output+="${output:+, }${current}"
    perfdata+="${perfdata:+ }'$k'=${perf[$k]};${warn[$k]};${crit[$k]}"
done

echo "${STATUS_TEXT[$state]}: $output|$perfdata"
(IFS=$'\n'; [[ -n $long_output ]] && echo "${long_output[*]}")
exit "$state"
