#! /bin/sh

if test "$#" != 1
then
    echo "Usage: ${0##*/} filename" >&2
    exit 1
fi

editfile="$1"
shift

# Create a temporary filename so we can do some judo.
tmpfile=$(mktemp -t "muttedit.XXXXXXXXXX")

# Now parse out the Sent-To line; the value of this field is our desired
# identity.
NEW_FROM_ADDR=$(sed -ne '/^Sent-To: /,0s/^Sent-To: //p' "$editfile")

cp "$editfile" ~/tmp/foo

# If a Sent-To line was supplied to us, then we need to do something clever.
if test -n "$NEW_FROM_ADDR"
then
    # Now, do the replacement and get rid of the Sent-To line.
    sed -e "s/^From: \\(.*\\)<\\(.*\\)>/From: \\1<$NEW_FROM_ADDR>/" "$editfile" > "$tmpfile"
    awk -v blanks=0 -- 'blanks >= 2 { print; }; /^$/ { blanks++; }; blanks == 1 && /^Sent-To: / { blanks++; print ""; }; blanks == 0 { print; }' "$tmpfile" > "$editfile"
fi

# Now edit it as normal.
exec ${MUTT_EDITOR:-${VISUAL:-${EDITOR:-vi}}} "$editfile"
