#!/bin/bash

# Set your exact location (Nagios Global Headquarters)
LAT="44.973N"
LON="93.155W"

# sunwait outputs values in clean 24-hour HH:MM format
# We use nautical because the program actually shows the end of nautical, which is the start of astronomical
DAWN=$(${HOME}/NWC2026-AstropotaPOD/sunwait list dawn nautical $LAT $LON)
DUSK=$(${HOME}/NWC2026-AstropotaPOD/sunwait list dusk nautical $LAT $LON)

# From here, it's Nagios API time
# Your Nagios XI API Details
XI_URL="http://192.168.123.16/nagiosxi/api/v1"
API_KEY="YOUR NAGIOS XI API KEY"

# Build the new time strings
# Day string becomes: "05:42-20:14"
# Night string becomes: "00:00-05:42,20:14-24:00"
DAY_RANGE="${DAWN}-${DUSK}"
NIGHT_RANGE="00:00-${DAWN},${DUSK}-24:00"

# Ensure our Timeperiods exist the way we want
curl -XPOST "${XI_URL}/config/timeperiod/AstropotaPOD-day?apikey=${API_KEY}&pretty=1" \
	-d "timeperiod_name=AstropotaPOD-day&alias=Local+Daytime+recalculated+via+cron&sunday=${DAY_RANGE}&monday=${DAY_RANGE}&tuesday=${DAY_RANGE}&wednesday=${DAY_RANGE}&thursday=${DAY_RANGE}&friday=${DAY_RANGE}&saturday=${DAY_RANGE}"
curl -XPOST "${XI_URL}/config/timeperiod/AstropotaPOD-night?apikey=${API_KEY}&pretty=1" \
	-d "timeperiod_name=AstropotaPOD-night&alias=Local+Nighttime+recalculated+via+cron&sunday=${NIGHT_RANGE}&monday=${NIGHT_RANGE}&tuesday=${NIGHT_RANGE}&wednesday=${NIGHT_RANGE}&thursday=${NIGHT_RANGE}&friday=${NIGHT_RANGE}&saturday=${NIGHT_RANGE}"

# Tell Nagios XI to safely apply the changes to the engine
curl -XPOST "${XI_URL}/system/applyconfig?apikey=${API_KEY}"
