#!/bin/bash

# API_URL="https://rspamd.deeproot.in/checkv2"
API_URL="http://localhost:11334/checkv2"
API_PASSWORD="RSPAMD_PASS"

if [ "$#" -ne 2 ]; then
  echo "usage: $0 APIVERSION QUEUEFILENAME" 1>&2
  exit 1
fi

apiver="$1"
queue_file="$2"

if [ "$apiver" != "v1" ]; then
  echo "wrong APIVERSION: $apiver" 1>&2
  exit 2
fi

# Call rspamd via HTTP API
rspamd_output=$(curl -s --data-binary @"$queue_file" -H "Password: $API_PASSWORD" "$API_URL")
if [ $? -ne 0 ]; then
  echo "Error contacting rspamd" 1>&2
  exit 3
fi

# Extract spam score from JSON response
spam_score=$(echo "$rspamd_output" | jq -r '.score')

# Validate spam score
if [[ ! $spam_score =~ ^-?[0-9]+(\.[0-9]+)?$ ]]; then
  echo "Error parsing rspamd output" 1>&2
  exit 4
fi

# Output for PMG
echo "v1"
if (( $(echo "$spam_score > 0" | bc -l) )); then
  echo "SCORE: $spam_score"
else
  echo "OK"
fi
