#!/bin/bash

#
# Watchdog check binary that checks for a maximum uptime
# The maximum uptime is read from the $MAX_WD_UPTIME_FILE file (in seconds).
#
# If this script exits with a non-zero status code the watchdog daemon will
# reboot the system.

MAX_WD_UPTIME_FILE=/run/spxsysconf/wd-max-uptime

# the watchdog daemon interprets the exit status as an errno value,
# these are the values for Linux.
ENOENT=2
EINVAL=22
ETIME=62

# exit on any unexpected error
set -e

# If this is placed in the watchdog daemon test directory it can be called as repair binary
[ "$1" != "repair" ] || exit $EINVAL

# Read the maximum allowed time
[ -r $MAX_WD_UPTIME_FILE ] || exit $ENOENT
MAX=$(< $MAX_WD_UPTIME_FILE)
[ -n "$MAX" ] || exit $EINVAL

# First /proc/uptime entry is seconds of uptime, with possible decimal part
[ -r /proc/uptime ] || exit $ENOENT
UPTIME_SECS="$(< /proc/uptime)"
UPTIME_SECS="${UPTIME_SECS%% *}"
UPTIME_SECS="${UPTIME_SECS%%.*}"

[ "$UPTIME_SECS" -le "$MAX" ] || exit $ETIME

exit 0
