Files
bubu-server-scripts/remove_nonexistent_rules.sh
2025-04-13 16:21:50 +02:00

66 lines
1.7 KiB
Bash
Executable File

#!/bin/zsh
# Script Version: 01
# Description: Removes non-existent rules from SpamAssassin local.cf configuration file.
# Variables
# ========
CONFIG_FILE="/etc/mail/spamassassin/local.cf"
BACKUP_FILE="/etc/mail/spamassassin/local.cf.bak"
TEMP_FILE=$(mktemp /tmp/local.cf.temp.XXXXXX)
# Backup original config
# ========
if ! cp "$CONFIG_FILE" "$BACKUP_FILE"; then
echo "Error: Backup of $CONFIG_FILE to $BACKUP_FILE failed. Aborting." >&2
exit 1
fi
echo "Backup of local.cf saved to $BACKUP_FILE"
# Extract non-existent rules from SpamAssassin lint output
# ========
RULES=$(spamassassin --lint -D 2>&1 | grep 'warning: score set for non-existent rule' | awk '{print $NF}' | sort | uniq)
if [ -z "$RULES" ]; then
echo "No non-existent rules found in the lint output."
rm -f "$TEMP_FILE" # Clean up the temporary file
exit 0
fi
echo "Non-existent rules to be removed:"
echo "$RULES"
# Remove non-existent rules from the config file
# ========
cp "$CONFIG_FILE" "$TEMP_FILE"
while read -r RULE; do
sed -i "/^score\s\+$RULE\b/d" "$TEMP_FILE"
done <<< "$RULES"
# Overwrite the original config
# ========
if mv "$TEMP_FILE" "$CONFIG_FILE"; then
echo "Non-existent rules removed from $CONFIG_FILE"
else
echo "Error: Failed to update $CONFIG_FILE. Aborting." >&2
rm -f "$TEMP_FILE" # Clean up in case of failure
exit 1
fi
# Restart SpamAssassin to apply changes
# ========
echo "Restarting SpamAssassin..."
if systemctl restart spamassassin; then
echo "SpamAssassin restarted successfully."
if ! systemctl is-active --quiet spamassassin; then
echo "Error: SpamAssassin is not active after restart." >&2
exit 1
fi
else
echo "Error: Failed to restart SpamAssassin." >&2
exit 1
fi
exit 0