#!/bin/sh
# pfSense → CRM Webhook Notifier
# Place this file on pfSense at: /usr/local/bin/crm_notify.sh
# Then make it executable: chmod +x /usr/local/bin/crm_notify.sh
#
# In pfSense: System → Advanced → Notifications → Command
# Set "Command" to: /usr/local/bin/crm_notify.sh "%subject%" "%message%"

CRM_WEBHOOK="https://crm.altriacallcenter.com/api/webhooks/email/"
WEBHOOK_SECRET=""   # leave blank unless you set EMAIL_WEBHOOK_SECRET in Django

SUBJECT="$1"
BODY="$2"
TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S UTC')

# If called with no args (test), use defaults
if [ -z "$SUBJECT" ]; then
    SUBJECT="pfSense Alert"
fi
if [ -z "$BODY" ]; then
    BODY="Alert triggered at $TIMESTAMP"
fi

# Detect priority from subject/body
detect_priority() {
    TEXT=$(echo "$SUBJECT $BODY" | tr '[:upper:]' '[:lower:]')
    case "$TEXT" in
        *down*|*offline*|*unreachable*|*outage*|*critical*|*failed*|*failure*)
            echo "critical" ;;
        *loss*|*latency*|*degraded*|*alarm*|*warning*|*error*)
            echo "high" ;;
        *up*|*recovered*|*restored*|*online*)
            echo "medium" ;;
        *)
            echo "high" ;;
    esac
}

PRIORITY=$(detect_priority)

# Build summary from subject
SUMMARY="pfSense Alert: $SUBJECT — $TIMESTAMP"

# Escape for JSON
json_escape() {
    printf '%s' "$1" | sed 's/\\/\\\\/g; s/"/\\"/g; s/$/\\n/g' | tr -d '\n' | sed 's/\\n$//'
}

SUBJECT_ESC=$(json_escape "$SUBJECT")
BODY_ESC=$(json_escape "$BODY")
SUMMARY_ESC=$(json_escape "$SUMMARY")

JSON="{
  \"subject\": \"[NETWORK] $SUBJECT_ESC\",
  \"from\": \"pfsense@altria.local\",
  \"from_name\": \"pfSense Firewall\",
  \"body\": \"$BODY_ESC\",
  \"email_id\": \"pfsense-$(date +%s)\",
  \"source\": \"email\",
  \"_ai_action\": \"ticket\",
  \"_ai_priority\": \"$PRIORITY\",
  \"_ai_sentiment\": \"neutral\",
  \"_ai_category\": \"network\",
  \"_ai_summary\": \"$SUMMARY_ESC\"
}"

# POST to CRM
if [ -n "$WEBHOOK_SECRET" ]; then
    curl -s -o /tmp/crm_response.txt -w "%{http_code}" \
        -X POST "$CRM_WEBHOOK" \
        -H "Content-Type: application/json" \
        -H "X-Webhook-Secret: $WEBHOOK_SECRET" \
        -d "$JSON" \
        --max-time 10 > /tmp/crm_http_code.txt 2>&1
else
    curl -s -o /tmp/crm_response.txt -w "%{http_code}" \
        -X POST "$CRM_WEBHOOK" \
        -H "Content-Type: application/json" \
        -d "$JSON" \
        --max-time 10 > /tmp/crm_http_code.txt 2>&1
fi

HTTP_CODE=$(cat /tmp/crm_http_code.txt)
RESPONSE=$(cat /tmp/crm_response.txt)

# Log result
LOG="/var/log/crm_notify.log"
if [ "$HTTP_CODE" = "201" ]; then
    echo "[$TIMESTAMP] ✓ Ticket created | Priority: $PRIORITY | Subject: $SUBJECT | Response: $RESPONSE" >> $LOG
else
    echo "[$TIMESTAMP] ✗ FAILED | HTTP: $HTTP_CODE | Subject: $SUBJECT | Response: $RESPONSE" >> $LOG
fi
