#!/usr/bin/env bash
# upcheck.sh - alert when a website goes DOWN, and again when it's back UP.
# Quiet otherwise, so it's safe to run every few minutes.
#
#   ./upcheck.sh https://example.com
#
# Run it every 5 minutes with cron (crontab -e):
#   */5 * * * * /home/you/upcheck.sh https://example.com
#
# "Up" = the page answers with HTTP 2xx or 3xx within 15 seconds. Remembers
# the last state in ~/.useralertx_upcheck/ so it only alerts on a change.
# API key: USERALERTX_API_KEY env var, else ~/.useralertx_key (create it
# once with uxsend.sh). USERALERTX_DRYRUN=1 prints instead of sending.

URL_API="${USERALERTX_URL:-https://useralertx.com/cgi-bin/itmessages.cgi}"
SITE="$1"
[ -z "$SITE" ] && { echo "usage: upcheck.sh https://your-site.example"; exit 2; }

send() {
  if [ -n "${USERALERTX_DRYRUN:-}" ]; then echo "[dry run] would send: $1"; return 0; fi
  local key="${USERALERTX_API_KEY:-}"
  [ -z "$key" ] && [ -f "$HOME/.useralertx_key" ] && key="$(tr -d '[:space:]' < "$HOME/.useralertx_key")"
  [ -z "$key" ] && { echo "upcheck: no API key (set USERALERTX_API_KEY or run uxsend.sh once to save it)"; return 1; }
  curl -s -o /dev/null -A 'UserAlertX-example-upcheck/1.0' -H "X-Api-Key: $key" --data-urlencode "body=$1" "$URL_API"
}

STATE_DIR="$HOME/.useralertx_upcheck"; mkdir -p "$STATE_DIR"
STATE_FILE="$STATE_DIR/$(printf '%s' "$SITE" | cksum | cut -d' ' -f1)"
LAST="$(cat "$STATE_FILE" 2>/dev/null || echo up)"

CODE="$(curl -s -o /dev/null -L --max-time 15 -w '%{http_code}' -A 'UserAlertX-upcheck/1.0' "$SITE")"
if [[ "$CODE" =~ ^[23] ]]; then NOW=up; else NOW=down; fi

if [ "$NOW" != "$LAST" ]; then
  if [ "$NOW" = down ]; then
    WHY=$([ "$CODE" = "000" ] && echo "no response" || echo "HTTP $CODE")
    send "DOWN: $SITE ($WHY) at $(date '+%H:%M %b %d')"
  else
    send "Back UP: $SITE (HTTP $CODE) at $(date '+%H:%M %b %d')"
  fi
  echo "$NOW" > "$STATE_FILE"
fi
echo "$SITE is $NOW (HTTP $CODE)"
