#!/bin/sh

# usage: make-parent.sh <filename> <filename> [<filename>]
# (make-parent.sh %F in Claws Mail)
# files in message/rfc822 format
# first file becomes a parent to the others, which must not already have parents

if [ -z "$2" ]; then echo "2+ arguments needed"; exit 1; fi
parent="$1"
parentId="$(sed -nE '1{h;$!d};x;/^\r?$/q;x;/^[[:blank:]]/{H;$!d}; x; s/^Message-ID[[:blank:]]*:\s*(.+)/\1/ip;T;q' "$parent")" # get parent's message id
if [ -z "$parentId" ]
then
	echo "$parent: Has no Message-ID"
	exit 1
fi

tempChild="$(mktemp)"

shift; for child # iterating through all arguments except first
do
	childReply="$(sed -nE '/^In-Reply-To[[:blank:]]*:/I=; /^References[[:blank:]]*:/I=; /^\r?$/q' "$child")" # check if child already has an In-Reply-To or References header
	if [ ! -z "$childReply" ]
	then
		echo "$child: already a child; skipping"
	else
		cp "$child" "$tempChild"
		echo "In-Reply-To:
 $parentId
References:
 $parentId" | cat - "$tempChild" > "$child"
	fi
done
rm "$tempChild"
exit 0
# SPDX-License-Identifier: Unlicense
