#!/bin/sh
set -e

PDIR="$HOME/tmp" 

mkdir -p "$PDIR"

infile="$(mktemp "$PDIR"/mutt_XXXXXX)"
tmpfile="$(mktemp "$PDIR"/mutt_XXXXXX)"
outfile="$(mktemp "$PDIR"/mutt_XXXXXX)"
mv "$outfile" "${outfile}.pdf"
outfile="${outfile}.pdf"

printf 'infile = %s\n' "$infile"
printf 'tmpfile = %s\n' "$tmpfile"
printf 'outfile = %s\n' "$outfile"

cat "${1:--}" > "$infile"

# join lines starting with space with previous line
sed -i '$!N;s/\n / /;P;D' "$infile"
sed -i '$!N;s/\n / /;P;D' "$infile"
sed -i '$!N;s/\n / /;P;D' "$infile"
sed -i '$!N;s/\n / /;P;D' "$infile"
sed -i '$!N;s/\n / /;P;D' "$infile"

echo "formatting $infile to groff format in $tmpfile"
mail_date="$(grep '^Date: ' "$infile")"
mail_from="$(grep '^From: ' "$infile")"
mail_to="$(grep '^To: ' "$infile" | tr ',' '\n')"
mail_cc="$(grep '^C[Cc]: ' "$infile" | tr ',' '\n')"
mail_subject="$(grep '^Subject: ' "$infile")"

{ 
    [ -n "$mail_subject" ] && printf ".TL\n%s\n" "$mail_subject" | sed 's/^Subject: //'; [ -n "$mail_from" ] && printf ".AU\n%s\n" "$mail_from";
    [ -n "$mail_to" ] && printf ".AU\n%s\n" "$mail_to";
    [ -n "$mail_cc" ] && printf ".AU\n%s\n" "$mail_cc";
    [ -n "$mail_date" ] && printf ".AI\n%s\n" "$mail_date";
    printf ".LP\n";
    grep -v "^Date:\|^From:\|^To:\|^Subject:\|^C[Cc]:\|^X-Mailer:\|^User-Agent:" "$infile" |\
        sed 's/^>\s*$//' |\
        sed 's/ *\(---*\)/\1\n/' |\
        sed '$!N;s/\n \([a-z]\)/ \1/;P;D' |\
        sed 's/^> *\(.*\)$/.I "\1"/' |\
        sed 's/ > / /g' |\
        sed 's/\(Fra\|Dato\|Til\|Emne\): /\n\1: /g' |\
        sed 's/\(From\|Date\|To\|C[Cc]\|Subject\): /\n\1: /g' |\
        sed 's/\(Links:\)/\n\1\n/g' |\
        sed 's/\(References:\)/\n\1\n/g';
    } > "$tmpfile"

echo "running groff $tmpfile $outfile"
preconv "$tmpfile" | groff -ms -T pdf > "$outfile"

rm "$infile" "$tmpfile"
xdg-open "$outfile"
