#!/bin/bash
#
# check_ping_by_hostname
#
# Attempts to resolve the name for and ping ourselves based on the device's
# hostname.
#

name="$HOSTNAME"

# Ensure $name is available
if [ -z "$name" ]; then
	echo "CRITICAL: No hostname(?!)"
	exit 2
fi

# Ensure we have the tools we need
for cmd in dig ping; do
	if ! command -v "$cmd" > /dev/null 2>&1; then
		echo "UNKNOWN: Missing command for check: $cmd"
		exit 3
	fi
done

# Ensure we can dig ourselves
if [ -z "$(dig +short "$name")" ]; then
	echo "CRITICAL: Could not resolve hostname or found empty record: $name"
	exit 2
fi

# Ping ourselves
if ! ping "$name" -c 1 > /dev/null 2>&1; then
	echo "CRITICAL: Could not ping self"
	exit 2
else
	echo "OK"
	exit 0
fi