Web Monitor Script

Simple script for monitoring of a web service using curl

#!/usr/bin/env bash

RETRIES=3
SLEEP=2
UPTIME=600
LOG="/var/log/${0}.log"

# Help
if [[ "$#" -lt 2 ]] ; then
        cat <<-EOF

        Web Monitor Script - Nimpen <nimpen@asbra.nu>

        Example:
        $0 https://google.com 'echo "Google is down!" | mail j@asbra.nu'

        EOF
        exit 1
fi

# Set Argument Values
[[ -n "$1" ]] && SITE="$1"
[[ -n "$1" ]] && COMMAND="$2"

# HTTP Status Codes
declare -A R=(
        [000]="Connection Failed"
        [200]="Successful"
        [301]="Moved Permanently" [302]="Moved Temporarily"
        [400]="Bad Request" [401]="Unauthorized" [403]="Forbidden" [404]="Not found"
        [500]="Internal Server Error" [502]="Bad Gateway" [503]="Service Unavailable" [504]="Gateway Timeout"
        )

# Curl Return Codes
declare -A E=(
        [0]="Successful"
        [6]="Could not resolve"
        [7]="Refused"
        [16]="HTTP/2 error"
        [28]="Time out"
        [35]="TLS/SSL connect error"
        [45]="Interface error"
        [52]="server did not reply"
        [56]="Failure in receiving network data"
        )

# Wait After Server Reboot
EPOCH_UPTIME=$(date -d"$(uptime -s)" +%s)
EPOCH_NOW=$(date +%s)
[[ "$((${EPOCH_NOW}-${EPOCH_UPTIME}))" -lt ${UPTIME} ]] && exit 1

# Check Service Availiability Loop
UP=0 ; CNT=0 ; while [[ ${UP} -ne 200 ]]
do
        let CNT++
        UP=$(curl --connect-timeout 1 -s -o /dev/null -w "%{http_code}" ${SITE})
        [[ ${UP} -ne 200 ]] && echo "$(date +'%Y-%m-%d %H:%M:%S') SITE:${SITE}, RETURN:${UP} ${R[$UP]}, EXIT:${?} ${E[$?]}, COUNT:${CNT}" | tee -a ${LOG}
        [[ ${CNT} -eq ${RETRIES} ]] && { $COMMAND ; exit 1 ; }
        sleep ${SLEEP}
done