#!/bin/bash
# mail2news-wrapper.sh - Privacy version

TEMP_DIR=$(mktemp -d)
RAW_EMAIL="$TEMP_DIR/raw_email.txt"
CLEANED_EMAIL="$TEMP_DIR/clean_email.txt"

# Leggi l'email da stdin
cat > "$RAW_EMAIL"

# Rimuovi la riga mbox "From " se presente
sed -i '1{/^From /d;}' "$RAW_EMAIL"

# === ESTRAI NEWSGROUP ===
NEWSGROUP=""

# Metodo 1: da X-Original-To header
ORIG_TO=$(grep -i "^X-Original-To:" "$RAW_EMAIL" | head -1)
if [ -n "$ORIG_TO" ]; then
    NEWSGROUP=$(echo "$ORIG_TO" | sed -n 's/.*mail2news-[0-9]*-\([^@]*\)@.*/\1/p')
fi

# Metodo 2: da Delivered-To header
if [ -z "$NEWSGROUP" ]; then
    DELIVERED_TO=$(grep -i "^Delivered-To:" "$RAW_EMAIL" | head -1)
    if [ -n "$DELIVERED_TO" ]; then
        NEWSGROUP=$(echo "$DELIVERED_TO" | sed -n 's/.*mail2news-[0-9]*-\([^@]*\)@.*/\1/p')
    fi
fi

# Metodo 3: dall'header Newsgroups già presente
if [ -z "$NEWSGROUP" ]; then
    NEWSGROUP=$(grep -i "^Newsgroups:" "$RAW_EMAIL" | head -1 | sed 's/^[Nn]ewsgroups:[[:space:]]*//')
fi

# Metodo 4: da argomento passato da Postfix ($1)
if [ -z "$NEWSGROUP" ] && [ -n "$1" ]; then
    NEWSGROUP=$(echo "$1" | sed -n 's/.*mail2news-[0-9]*-\([^@]*\)@.*/\1/p')
fi

# Se ancora non abbiamo il newsgroup, errore
if [ -z "$NEWSGROUP" ]; then
    rm -rf "$TEMP_DIR"
    exit 1
fi

# === COSTRUISCI L'EMAIL PULITA ===
grep -i "^From:" "$RAW_EMAIL" > "$CLEANED_EMAIL" || echo "From: anonymous@mail2news.tcpreset.net" > "$CLEANED_EMAIL"
grep -i "^Subject:" "$RAW_EMAIL" >> "$CLEANED_EMAIL" || echo "Subject: (No Subject)" >> "$CLEANED_EMAIL"

# Header Newsgroups
echo "Newsgroups: $NEWSGROUP" >> "$CLEANED_EMAIL"

# Header To
grep -i "^To:" "$RAW_EMAIL" >> "$CLEANED_EMAIL"

grep -i "^Message-ID:" "$RAW_EMAIL" >> "$CLEANED_EMAIL"
grep -i "^References:" "$RAW_EMAIL" >> "$CLEANED_EMAIL"
grep -i "^In-Reply-To:" "$RAW_EMAIL" >> "$CLEANED_EMAIL"

# Header X-*
grep -i "^X-Ed25519-Sig:" "$RAW_EMAIL" >> "$CLEANED_EMAIL"
grep -i "^X-Ed25519-Pub:" "$RAW_EMAIL" >> "$CLEANED_EMAIL"
grep -i "^X-No-Archive:" "$RAW_EMAIL" >> "$CLEANED_EMAIL"

# Header Face (VFACE identicon) - preserve folded continuation lines
awk '/^[Ff]ace:/{f=1;print;next} f==1 && /^[ \t]/{print;next} {f=0}' "$RAW_EMAIL" >> "$CLEANED_EMAIL"

echo "" >> "$CLEANED_EMAIL"

# Estrai il corpo
sed -n '/^$/,$p' "$RAW_EMAIL" | tail -n +2 >> "$CLEANED_EMAIL"

# Esegui mail2news
sudo -u mail2news /usr/local/bin/mail2news < "$CLEANED_EMAIL" 2>&1
RESULT=$?

# Pulisci
srm -rf "$TEMP_DIR"
exit $RESULT
