#!/bin/bash
#
# cauth_watchdog is special user to monitor SSSD liveness and cache freshness.
# See https://st.yandex-team.ru/CAUTH-269 for details
#
# Provides: cauth_cache


# Import file with CAuth functions
if [ -s /etc/cauth/cauth_functions ]; then
    . /etc/cauth/cauth_functions
else
    exit 1
fi

die () {
    echo "PASSIVE-CHECK:cauth_cache;$1;$2"
    exit 0
}

# getent mixes stderr & stdout in case of failure, so they are merged.
# Try `getent psswd foobar 2>/dev/null` and see it yourself :)
getent_out=$(getent passwd cauth_watchdog 2>&1)
getent_err=$?

now=$(date +%s)
# awk truncates negative values towards zero, so -0.75 hours becomes 0
lag_hours=$(echo "$getent_out" | awk -F: '($1 == "cauth_watchdog" && $5 ~ /^wdog_[0-9]+$/) {ts = substr($5, 6); print int( ('$now' - ts) / 3600); exit 0}')

if [ -z "$lag_hours" ]; then
    die 2 "No cauth_watchdog user found, getent output: <${getent_out}>, \$? = ${getent_err}"
elif [ -1 -lt "$lag_hours" -a "$lag_hours" -lt 4 ]; then
    die 0 "OK, CAuth cache is ${lag_hours} hours old"
else
    die 1 "CAuth cache is ${lag_hours} hours old"
fi
