#!/bin/bash
# Mail2News posting script — NeoMutt + torsocks + swaks
# Bind to F9 in neomuttrc.tor:
#   macro index,pager <F9> "<shell-escape>~/.config/neomutt/m2n-prompt.sh<enter>" "Post to Usenet"
set -euo pipefail

M2N_TO="mail2news@xilb7y4kj6u6qfo45o3yk2kilfv54ffukzei3puonuqlncy7cn2afwyd.onion"
SMTP_HOST="xilb7y4kj6u6qfo45o3yk2kilfv54ffukzei3puonuqlncy7cn2afwyd.onion"
SMTP_PORT="25"
FROM="nobody@virebent.invalid"

clear
echo "=== MAIL2NEWS — Usenet Post ==="
echo

printf "Newsgroup(s) [comma-separated]: "
read -r NEWSGROUP
[ -z "$NEWSGROUP" ] && echo "Aborted." && exit 1
NEWSGROUP=$(echo "$NEWSGROUP" | sed 's/ *, */,/g')

printf "Subject: "
read -r SUBJECT
[ -z "$SUBJECT" ] && echo "Aborted." && exit 1

REFERENCES=""
if echo "$SUBJECT" | grep -qi "^re:"; then
    printf "References (Message-ID of original): "
    read -r REFERENCES
fi

MSGFILE=$(mktemp /tmp/m2n-body.XXXXXX)
echo "" > "$MSGFILE"
echo "-- " >> "$MSGFILE"
echo "posted via virebent.art mail2news" >> "$MSGFILE"

${EDITOR:-vim} "$MSGFILE"

DRAFTFILE=$(mktemp /tmp/m2n-draft.XXXXXX)
{
    printf "To: %s\n"          "$M2N_TO"
    printf "From: %s\n"        "$FROM"
    printf "Subject: %s\n"     "$SUBJECT"
    [ -n "$REFERENCES" ] && printf "References: %s\n" "$REFERENCES"
    printf "Newsgroups: %s\n"  "$NEWSGROUP"
    printf "\n"
    cat "$MSGFILE"
} > "$DRAFTFILE"

clear
echo "=== REVIEW ==="
cat "$DRAFTFILE"
echo
printf "[s]end  [e]dit  [q]uit: "
read -r CHOICE

case "$CHOICE" in
    e|E) ${EDITOR:-vim} "$DRAFTFILE" ;;
    q|Q) rm -f "$MSGFILE" "$DRAFTFILE"; echo "Cancelled."; exit 0 ;;
esac

echo
echo "Sending via Tor..."

torsocks swaks \
    --server "${SMTP_HOST}:${SMTP_PORT}" \
    --from   "$FROM" \
    --to     "$M2N_TO" \
    --data   "@${DRAFTFILE}" \
    --timeout 60 \
    2>&1 | tee /tmp/m2n-smtp.log

if grep -q "250 " /tmp/m2n-smtp.log; then
    echo
    echo "Sent to: $NEWSGROUP"
else
    echo
    echo "ERROR — check /tmp/m2n-smtp.log"
fi

rm -f "$MSGFILE" "$DRAFTFILE"
printf "\nPress Enter to return to NeoMutt..."
read -r
