#!/bin/sh
# Download mail from GCC list archive.

if [[ $* == '' || $* == '--help' ]]
then
  echo "Usage: $0 https://gcc.gnu.org/ml/list/YYYY-MM/msgNNNNN.html" >&2
  test $# -eq 1
  exit
fi

urldecode() {
  awk -niord '{printf RT?$0chr("0x"substr(RT,2)):$0}' RS=%..
}

set -xe
draft=`mktemp /dev/shm/gcc-patches.XXXXXX`
for i in "$@"
do
  list=${i#*gcc.gnu.org/pipermail/}
  list=${list%%/*}
  echo "CC: $list@gcc.gnu.org" > $draft
  curl --silent --fail "$i" | sed -n '/LINK REL="made"/{s/^.*="mailto:/To: /;s/?Subject=Re:%20/%0aSubject: /;s/&In-Reply-To=/%0aIn-Reply-To: /;s/">$/%0a%0a/p}' | urldecode >> $draft
  mutt -H $draft -- "$(awk '/^To:/{print $2}' $draft)"
done
