diff --git a/mcapi.sh b/mcapi.sh new file mode 100755 index 0000000..4027618 --- /dev/null +++ b/mcapi.sh @@ -0,0 +1,57 @@ +#!/bin/bash + +# decription: This script uses mcapi.us to determine +# the status of a Minecraft server and reports +# its findings back to a Healthchecks instance +# at $HEALTHCHECKS_URL. +# +# author: david@socialnerds.org +# version: 0.1 +# license: MIT +# +# usage: ./mcapi.sh + +MCAPI_URL="https://mcapi.us/server" +CURL_OPTIONS="-fsS -m 10 --retry 5" +CURL_CMD="curl $CURL_OPTIONS" +HEALTHCHECKS_URL="https://checks.socialnerds.org/ping" +DEPENDENCIES="curl jq" + +# check for missing dependencies (and exit on failure) +for DEPENDENCY in $DEPENDENCIES; do + if [ ! $(command -v $DEPENDENCY) ]; then + echo "missing dependency [$DEPENDENCY]" + exit 2 + fi +done + +# signal script start to healthchecks +if [ $2 ]; then + HEALTHCHECKS_ID="$2" + $CURL_CMD -o /dev/null $HEALTHCHECKS_URL/$HEALTHCHECKS_ID/start +fi + +# get server status +if [ $1 ]; then + IP="$1" + URL="$MCAPI_URL/status?ip=$IP" + STATUS=$($CURL_CMD $URL | jq --raw-output '.status') + if [ $STATUS == "success" ]; then + NOW=$($CURL_CMD $URL | jq --raw-output '.players.now') + MAX=$($CURL_CMD $URL | jq --raw-output '.players.max') + # signal script success to healthchecks + if [ $HEALTHCHECKS_ID ]; then + $CURL_CMD -o /dev/null --data-raw "Online players: $NOW/$MAX" $HEALTHCHECKS_URL/$HEALTHCHECKS_ID + fi + else + # signal script failure to healthchecks + if [ $HEALTHCHECKS_ID ]; then + $CURL_CMD -o /dev/null $HEALTHCHECKS_URL/$HEALTHCHECKS_ID/fail + fi + fi +else + echo "first option must be the hostname/ip of a minecraft server" + exit 1 +fi + +exit 0