#!/usr/bin/env bash
#
# onx-modsec-custom-rule-write — Özel SecRule'leri Apache'ye yaz.
#
# Input: {"rule_id":N, "name":"...", "rule_content":"SecRule ...", "is_enabled":bool, "domain_name":"opt", "action":"delete|write"}
# Output: {"applied":true, "file":"...", "syntax_ok":bool, "reloaded":bool}

set -euo pipefail

readonly CONF_DIR="/etc/httpd/modsecurity.d/onox-custom.d"
readonly LOG_TAG="onox-modsec-custom"

input="$(cat)"
rule_id=$(echo "$input" | jq -r '.rule_id // 0')
name=$(echo "$input"    | jq -r '.name // ""')
content=$(echo "$input" | jq -r '.rule_content // ""')
enabled=$(echo "$input" | jq -r '.is_enabled // true')
domain=$(echo "$input"  | jq -r '.domain_name // empty')
action=$(echo "$input"  | jq -r '.action // "write"')

if ! [[ "$rule_id" =~ ^[0-9]+$ ]] || (( rule_id < 1 )); then
    jq -nc '{ok:false,error:"valid rule_id required"}' >&2
    exit 1
fi

mkdir -p "$CONF_DIR"
chmod 0755 "$CONF_DIR"

readonly FILE="$CONF_DIR/rule-${rule_id}.conf"

# Delete action
if [[ "$action" == "delete" ]]; then
    rm -f "$FILE"
    httpd -t 2>/dev/null && systemctl reload httpd 2>/dev/null && reloaded=true || reloaded=false
    jq -nc --argjson reloaded "$reloaded" '{ok:true, applied:true, action:"deleted", reloaded:$reloaded}'
    exit 0
fi

# Write action
if [[ -z "$content" ]]; then
    jq -nc '{ok:false,error:"rule_content required for write action"}' >&2
    exit 1
fi

# Basic syntax check: SecRule, SecAction, veya SecMarker satırı içermeli
if ! echo "$content" | grep -qE '^\s*Sec(Rule|Action|MarkerEnd)'; then
    jq -nc '{ok:false,error:"no valid SecRule/SecAction directive found"}' >&2
    exit 3
fi

# Generate config file
{
    echo "# Onoxsoft Panel custom rule"
    echo "# Name: $name"
    echo "# ID: $rule_id"
    echo "# Enabled: $enabled"
    echo "# Generated: $(date -u +%Y-%m-%dT%H:%M:%SZ)"
    echo ""

    if [[ "$enabled" != "true" ]]; then
        # Comment out all rule lines
        echo "$content" | sed 's/^/# DISABLED: /'
    else
        if [[ -n "$domain" ]]; then
            echo "<If \"req('Host') == '$domain'\">"
            echo "$content"
            echo "</If>"
        else
            echo "$content"
        fi
    fi
} > "$FILE"

chmod 0644 "$FILE"

# Apache config test
syntax_ok=true
if command -v httpd &>/dev/null; then
    if ! httpd -t 2>/tmp/onox-syntax-err-$$; then
        syntax_ok=false
        err="$(cat /tmp/onox-syntax-err-$$ 2>/dev/null || echo unknown)"
        rm -f /tmp/onox-syntax-err-$$
        # Rollback — kuralı sil
        rm -f "$FILE"
        jq -nc --arg err "$err" '{ok:false, error:"Apache syntax check failed", apache_err:$err}' >&2
        exit 4
    fi
    rm -f /tmp/onox-syntax-err-$$
fi

reloaded=true
if command -v systemctl &>/dev/null; then
    systemctl reload httpd 2>/dev/null || reloaded=false
fi

logger -t "$LOG_TAG" "Wrote rule_id=$rule_id name=$name enabled=$enabled reloaded=$reloaded"

jq -nc \
    --arg file "$FILE" \
    --argjson syntax_ok "$syntax_ok" \
    --argjson reloaded "$reloaded" \
    '{ok:true, applied:true, file:$file, syntax_ok:$syntax_ok, reloaded:$reloaded}'
