#!/usr/bin/env bash
# uxsend.sh - send yourself a UserAlertX alert (Mac / Linux, needs curl).
#
#   chmod +x uxsend.sh
#   ./uxsend.sh                         # asks "Enter text body"
#   ./uxsend.sh "Backup finished"       # one-shot
#   some_long_job && ./uxsend.sh "Job done" || ./uxsend.sh "Job FAILED"
#   ./uxsend.sh -m sms "Server is back"  # force text (-m email = email)
#
# API key: USERALERTX_API_KEY env var, else ~/.useralertx_key, else it asks
# (and can save it there, readable only by you). Your key is on your
# account page (useralertx.com -> Account).

URL="${USERALERTX_URL:-https://useralertx.com/cgi-bin/itmessages.cgi}"
KEYFILE="$HOME/.useralertx_key"
METHOD=""
if [ "$1" = "-m" ]; then METHOD="$2"; shift 2; fi

KEY="${USERALERTX_API_KEY:-}"
[ -z "$KEY" ] && [ -f "$KEYFILE" ] && KEY="$(tr -d '[:space:]' < "$KEYFILE")"
if [ -z "$KEY" ]; then
  echo "Your API key is on your UserAlertX account page (useralertx.com -> Account)."
  read -r -p "Paste your API key: " KEY
  [ -z "$KEY" ] && { echo "No API key entered - stopping."; exit 1; }
  read -r -p "Save it in $KEYFILE? (y/N) " SAVE
  if [[ "$SAVE" =~ ^[yY] ]]; then (umask 077; printf '%s' "$KEY" > "$KEYFILE"); echo "Saved."; fi
fi

send() {
  local args=(-s -w '\n%{http_code}' -A 'UserAlertX-example-sh/1.0' -H "X-Api-Key: $KEY" --data-urlencode "body=$1")
  [ -n "$METHOD" ] && args+=(--data-urlencode "method=$METHOD")
  local out code json
  out="$(curl "${args[@]}" "$URL")" || { echo "Could not reach UserAlertX."; return 1; }
  code="${out##*$'\n'}"; json="${out%$'\n'*}"
  case "$code" in
    200) echo "Sent: $json" ;;
    202) echo "Held (recipient hasn't replied START yet): $json" ;;
    *)   echo "Not sent (HTTP $code): $json"; return 1 ;;
  esac
}

if [ $# -gt 0 ]; then send "$*"; exit $?; fi

echo "UserAlertX - send yourself an alert (Enter on an empty message to quit)."
while true; do
  read -r -p "Enter text body: " BODY
  [ -z "$BODY" ] && break
  send "$BODY"
done
