#!/bin/sh
# pfSense Gateway Monitor → CRM
# Runs every minute via cron, detects gateway state changes, creates CRM tickets
# Place at: /usr/local/bin/crm_gateway_check.sh
# chmod +x /usr/local/bin/crm_gateway_check.sh
#
# Add to pfSense cron (Services → Cron):
#   * * * * * root /usr/local/bin/crm_gateway_check.sh

CRM_WEBHOOK="https://crm.altriacallcenter.com/api/webhooks/email/"
STATE_FILE="/tmp/crm_gw_state"
LOG="/var/log/crm_notify.log"
TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S UTC')

# Load previous state
if [ -f "$STATE_FILE" ]; then
    PREV_STATE=$(cat "$STATE_FILE")
else
    PREV_STATE=""
fi

# Get current gateway status from pfSense
# This reads the dpinger status for all gateways
CURRENT_STATE=""
GW_DOWN=""
GW_UP=""

# Parse gateway status using pfSense PHP
GW_STATUS=$(/usr/local/bin/php -r "
require_once('/etc/inc/gwlb.inc');
require_once('/etc/inc/util.inc');
\$gateways = return_gateways_status(true);
foreach (\$gateways as \$name => \$gw) {
    \$status = strtolower(\$gw['status'] ?? 'none');
    echo \$name . '=' . \$status . '\n';
}
" 2>/dev/null)

if [ -z "$GW_STATUS" ]; then
    # Fallback: read directly from dpinger
    GW_STATUS=$(netstat -rn | grep -v '^$' | awk 'NR>4{print $1"=unknown"}' 2>/dev/null)
fi

CURRENT_STATE="$GW_STATUS"

# Compare with previous state and detect changes
echo "$GW_STATUS" | while IFS='=' read -r GW_NAME GW_STAT; do
    [ -z "$GW_NAME" ] && continue

    PREV=$(echo "$PREV_STATE" | grep "^${GW_NAME}=" | cut -d= -f2)

    if [ "$GW_STAT" != "$PREV" ]; then
        # State changed — determine what happened
        case "$GW_STAT" in
            *down*|*loss*|*delay*|*alarm*)
                PRIORITY="critical"
                SUBJECT="[NETWORK DOWN] Gateway $GW_NAME is DOWN"
                BODY="Gateway: $GW_NAME\nStatus: DOWN\nPrevious: $PREV\nTime: $TIMESTAMP\n\nImmediate attention required."
                ACTION="ticket"
                ;;
            *online*|*none*|*up*)
                if echo "$PREV" | grep -qiE 'down|loss|delay|alarm'; then
                    PRIORITY="medium"
                    SUBJECT="[NETWORK UP] Gateway $GW_NAME RECOVERED"
                    BODY="Gateway: $GW_NAME\nStatus: RECOVERED (back online)\nPrevious: $PREV\nTime: $TIMESTAMP"
                    ACTION="ticket"
                else
                    continue
                fi
                ;;
            *)
                continue
                ;;
        esac

        # POST to CRM
        SUBJECT_ESC=$(printf '%s' "$SUBJECT" | sed 's/"/\\"/g')
        BODY_ESC=$(printf '%s' "$BODY" | sed 's/"/\\"/g; s/$/\\n/g' | tr -d '\n')
        SUMMARY_ESC="$SUBJECT_ESC — $TIMESTAMP"

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

        HTTP_CODE=$(curl -s -o /tmp/crm_gw_resp.txt -w "%{http_code}" \
            -X POST "$CRM_WEBHOOK" \
            -H "Content-Type: application/json" \
            -d "$JSON" \
            --max-time 10)

        RESPONSE=$(cat /tmp/crm_gw_resp.txt 2>/dev/null)

        if [ "$HTTP_CODE" = "201" ]; then
            echo "[$TIMESTAMP] ✓ $SUBJECT | HTTP: $HTTP_CODE | $RESPONSE" >> $LOG
        else
            echo "[$TIMESTAMP] ✗ FAILED: $SUBJECT | HTTP: $HTTP_CODE | $RESPONSE" >> $LOG
        fi
    fi
done

# Save current state
echo "$CURRENT_STATE" > "$STATE_FILE"
