#!/bin/bash
# send-ntfy - Send notification via ntfy using credentials from ~/.env

set -euo pipefail

# Load credentials from ~/.env
if [ -f "$HOME/.env" ]; then
    set -a
    source "$HOME/.env"
    set +a
else
    echo "Error: ~/.env not found" >&2
    exit 1
fi

# Check for URL
if [ -z "${NTFY_URL:-}" ]; then
    echo "Error: NTFY_URL must be set in ~/.env" >&2
    exit 1
fi

# Add https:// if missing
if [[ ! "$NTFY_URL" =~ ^https?:// ]]; then
    NTFY_URL="https://$NTFY_URL"
fi

# Parse arguments
TOPIC="${1:-alerts}"
MESSAGE="${2:-}"
TITLE="${3:-}"
PRIORITY="${4:-default}"
TAGS="${5:-}"

if [ -z "$MESSAGE" ]; then
    echo "Usage: send-ntfy <topic> <message> [title] [priority] [tags]" >&2
    echo "" >&2
    echo "Examples:" >&2
    echo "  send-ntfy alerts 'Backup completed'" >&2
    echo "  send-ntfy security 'Suspicious login' 'Security Alert' urgent 'warning,shield'" >&2
    echo "  send-ntfy personal 'Meeting in 5 minutes'" >&2
    exit 1
fi

# Build full URL with topic
FULL_URL="$NTFY_URL/$TOPIC"

# Build curl options array
CURL_OPTS=(
    -s
    --http1.1
    -w "\n%{http_code}"
    -d "$MESSAGE"
)

# Add authentication
if [ -n "${NTFY_TOKEN:-}" ]; then
    CURL_OPTS+=(-H "Authorization: Bearer $NTFY_TOKEN")
elif [ -n "${NTFY_AUTH:-}" ]; then
    CURL_OPTS+=(-u "$NTFY_AUTH")
else
    echo "Error: NTFY_TOKEN or NTFY_AUTH must be set in ~/.env" >&2
    exit 1
fi

# Add optional headers
[ -n "$TITLE" ] && CURL_OPTS+=(-H "Title: $TITLE")
[ -n "$PRIORITY" ] && CURL_OPTS+=(-H "Priority: $PRIORITY")
[ -n "$TAGS" ] && CURL_OPTS+=(-H "Tags: $TAGS")

# Send notification
RESULT=$(curl "${CURL_OPTS[@]}" "$FULL_URL" 2>&1)

# Extract HTTP code
HTTP_CODE=$(echo "$RESULT" | tail -1)
RESPONSE=$(echo "$RESULT" | sed '$d')

if [ "$HTTP_CODE" = "200" ]; then
    echo "✅ Notification sent to $TOPIC"
    exit 0
else
    echo "❌ Failed: HTTP $HTTP_CODE" >&2
    [ -n "$RESPONSE" ] && echo "Response: $RESPONSE" >&2
    exit 1
fi
