#!/bin/sh

STATE_OK=0 # define the exit code if status is OK
STATE_WARNING=1 # define the exit code if status is Warning
STATE_CRITICAL=2 # define the exit code if status is Critical
STATE_UNKNOWN=3 # define the exit code if status is Unknown

while getopts "w:c:" Input;
do
       case ${Input} in
       w)      warn=${OPTARG};;
       c)      crit=${OPTARG};;

       esac
done

CertExpires=`/opt/jdk-13/bin/keytool -list -v -cacerts -storepass "changeit" | grep -PA 7 '(Alias name: ws002302\.schaeffler\.com)(?!\s)' | grep -i until | sed 's/.*until: //'`
warndays=$(date -d "${CertExpires}-${warn}days" "+%s")
critdays=$(date -d "${CertExpires}-${crit}days" "+%s")
datetoday=$(date +"%s")
certdays=$(date -d "${CertExpires}" +%s)
dayslefts=$(($certdays - $datetoday))
daysleft=$(($dayslefts / 86400))


if [ $datetoday -ge $critdays ];then echo "Critical - will expire on $CertExpires | 'certdays' = $daysleft [d]"; exit ${STATE_CRITICAL}
elif [ $datetoday -ge $warndays ];then echo "Warning - will expire on $CertExpires | 'certdays' = $daysleft [d]"; exit ${STATE_WARNING}
else echo "OK - will expire on $CertExpires | 'certdays'=$daysleft [d]"; exit ${STATE_OK}
fi