#!/bin/bash

notify_host="https://notify.astropotamus.com"
chanDefault="POD"
alertType=""
msgTitle=""
message=""
tag="exclamation"
priority="3"
state=""
testMode=""

### Define command for service
### define command {
###    command_name    notify-service-by-ntfy
###    command_line    $USER1$/notify-by-ntfy.sh -t service -ha "$HOSTALIAS$" -h "$HOSTNAME$" -hs "$HOSTSTATE$" -ld "$LONGDATETIME$" -nt "$NOTIFICATIONTYPE$" -s "$SERVICEDESC$" -ss "$SERVICESTATE$"
### }

while [ -n "$1" ]; do
  case "$1" in
    --test) testMode="true"; shift 1;;
    -C|--channel) channel="$2"; shift 1;;
    -t|--type) alertType="$2"; shift 2;;
    -ha) NAGIOS_HOSTALIAS="$2"; shift 2;;
    -h) NAGIOS_HOSTNAME="$2"; shift 2;;
    -hs) NAGIOS_HOSTSTATE="$2"; shift 2;;
    -ld) NAGIOS_LONGDATETIME="$2"; shift 2;;
    -nt) NAGIOS_NOTIFICATIONTYPE="$2"; shift 2;;
    -s) NAGIOS_SERVICEDESC="$2"; shift 2;;
    -ss) NAGIOS_SERVICESTATE="$2"; shift 2;;
    *) shift 1;;
  esac
done

[ -z "$channel" ] && channel="$chanDefault"

case "$NAGIOS_NOTIFICATIONTYPE" in
  PROBLEM) tag="bangbang";;
  RECOVERY) tag="ok";;
  ACKNOWLEDGEMENT) tag="ok_hand";;
  FLAPPINGSTART) tag="hatched_chick";;
  FLAPPINGSTOP) tag="hourglass_flowing_sand";;
  DOWNTIMESTART) tag="sleeping_bed";;
  DOWNTIMEEND) tag="sunny";;
  *) tag="exclamation";;
esac

case "$NAGIOS_HOSTSTATE" in
  0) tag="$tag,+1";;
  1) tag="$tag,-1";;
  2) tag="$tag,-1";;
  3) tag="$tag,question";;
esac

case "$NAGIOS_SERVICESTATE" in
  0) tag="$tag,+1";;
  1) tag="$tag,-1";;
  2) tag="$tag,warning";;
  3) tag="$tag,question";;
esac

do_notify() {
  [ -n "$1" ] && channel="${channel}-${1}"
  curl -s \
        -H "Title: ${msgTitle}" \
        -H "Tags: ${tag}" \
        -H "Priority: ${priority}" \
        -d "${message}" \
        ${notify_host}/${channel}
}

do_host() {
  msgTitle="HOST ${NAGIOS_NOTIFICATIONTYPE}"
  message="$NAGIOS_NOTIFICATIONTYPE $NAGIOS_HOSTNAME is $NAGIOS_HOSTSTATE $NAGIOS_LONGDATETIME"
  do_notify "Hosts"
}

do_service() {
  msgTitle="SERVICE ${NAGIOS_NOTIFICATIONTYPE}"
  message="$NAGIOS_NOTIFICATIONTYPE $NAGIOS_SERVICEDESC @ $NAGIOS_HOSTALIAS is $NAGIOS_SERVICESTATE $NAGIOS_LONGDATETIME"
  do_notify "Services"
}

if [ -n "$testMode" ]; then
  NAGIOS_NOTIFICATIONTYPE="Test"
  NAGIOS_HOSTNAME="FakeHost"
  NAGIOS_HOSTSTATE="OK"
  NAGIOS_SERVICEDESC="FakeService"
  NAGIOS_HOSTALIAS="FakeHostAlias"
  NAGIOS_SERVICESTATE="OK"
  NAGIOS_LONGDATETIME="Today"
fi

case "$alertType" in
  h|host|host) do_host;;
  s|svc|service) do_service;;
  *) shift 1;;
esac

exit
