#!/bin/sh

# @file check-uptime
#
# Copyright (C) Metaswitch Networks 2016
# If license terms are provided to you in a COPYING file in the root directory
# of the source code repository by which you are accessing this code, then
# the license outlined in that COPYING file applies to your use.
# Otherwise no rights are granted except for those provided to you by
# Metaswitch Networks in a separate written agreement.

# Checks that a process has been running for at least REQUIRED_UPTIME
# seconds. Returns 0 if it has. Returns a non-zero value if it has not.
REQUIRED_UPTIME=30

# Bail out and return non-zero if anything goes wrong.
set -e

# The first command-line argument is the pidfile for the process.
# The second and third arguments are passed through to the script issue_alarm,
# for it to use to clear the process-not-ready alarm.
[ $# = 3 ] || { echo "Usage: check-uptime <pidfile> <issuer> <alarm>" >&2 ; exit 2 ; }
pidfile=$1
issuer=$2
alarm=$3

# It's expected that there might not be a pidfile.
pid=$( cat $pidfile 2>/dev/null)

value=$( ps -p $pid -o etimes= 2>/dev/null) || { echo "No process matching value from pidfile: $pid" >&2 ; exit 1 ; }
if [ "$value" -ge "$REQUIRED_UPTIME" ]; then
  /usr/share/clearwater/bin/issue-alarm "$issuer" "$alarm"
  exit 0
else
  exit 1
fi
