#!/usr/bin/env bash
# Sends a support@ email when today's Sitesmith spend crosses the alert threshold.
set -euo pipefail

LOCK=/var/lock/sitesmith-spend-alert.lock
exec 9>"$LOCK"
flock -n 9 || { echo "already running"; exit 0; }

SPENT=$(timeout 30 mysql --batch -N whp -e "SELECT COALESCE(SUM(cost_usd),0) FROM sitesmith_usage WHERE created_at >= CURDATE();")
CAP=$(jq -r '.sitesmith.max_cost_per_server_per_day_usd // 50' /docker/whp/settings.json)
PCT=$(jq -r '.sitesmith.alert_at_pct_of_server_cap     // 80' /docker/whp/settings.json)
THRESHOLD=$(awk -v c="$CAP" -v p="$PCT" 'BEGIN { printf "%.2f", c * p / 100 }')

CMP=$(awk -v s="$SPENT" -v t="$THRESHOLD" 'BEGIN { print (s+0 >= t+0) ? 1 : 0 }')
if [ "$CMP" = "1" ]; then
    STATE=/var/lib/whp/sitesmith-alert-state
    TODAY=$(date +%F)
    if [ -f "$STATE" ] && [ "$(cat "$STATE")" = "$TODAY" ]; then exit 0; fi
    mkdir -p "$(dirname "$STATE")"
    echo "$TODAY" > "$STATE"
    HOST=$(hostname)
    {
        echo "Subject: [Sitesmith] daily spend alert on $HOST"
        echo "To: support@anhonesthost.com"
        echo "From: noreply@$HOST"
        echo
        echo "Sitesmith spend on $HOST has crossed $PCT% of the daily cap."
        echo "Today: \$$SPENT  /  Cap: \$$CAP  /  Threshold: \$$THRESHOLD"
        echo
        echo "Top users today:"
        mysql whp -e "SELECT username, COUNT(*) AS calls, ROUND(SUM(cost_usd),4) AS usd FROM sitesmith_usage WHERE created_at >= CURDATE() GROUP BY username ORDER BY 3 DESC LIMIT 10;"
    } | /usr/sbin/sendmail -t
fi
