#! /bin/sh
# pnews [prefix] - prepare user's article on stdin for posting via relaynews
#	prefix is for tear; if given, output will also be in
#	${prefix}hdr & ${prefix}body

# =()<. ${NEWSCONFIG-@<NEWSCONFIG>@}>()=
. ${NEWSCONFIG-/etc/news/bin/config}

PATH=$NEWSCTL/bin:$NEWSBIN/inject:$NEWSBIN:$NEWSPATH; export PATH
prefix=/tmp/pn$$		# default prefix
hdrs=/tmp/pn$$hdrs		# 1036-conformant headers
rmlist="$inhdrs $inbody $hdrs"	# remove hdr & body files by default

umask $NEWSUMASK

# argument procesing
case $# in
0)	;;
1)
	prefix="$1"
	rmlist="$hdrs"		# only remove scratch file(s)
	;;
*)
	echo "usage: $0 [prefix]" >&2
	exit 1
	;;
esac
inhdrs=${prefix}hdr		# generated by tear: headers
inbody=${prefix}body		# generated by tear: body

# tear moved down into if because it might fail...

# generate new headers and bash old headers ** takes 2.1 seconds

# touch up headers & rewrite dates to make them 1036-compliant.
# canonicalise header keyword capitalisation;
# greps for Control: and Approved: later assume this, as does defhdrs.awk,
# so $inhdrs needs to stick around and be canonicalised.
if tear $prefix &&	# output in $inhdrs and $inbody ** takes 0.4 seconds
	canonhdr -dm <$inhdrs >$hdrs	# dredge up defaults ** takes 0.1 secs
then
	# are we a client of a server?
	if test -r $NEWSCTL/server
	then
		svr="`cat $NEWSCTL/server`"
		me="`hostname`"
		case "$me" in
		$svr)	args=				;;
		*)	args="-c $me -s $svr"		;;
		esac
	else
		args=
	fi

	# POLICY: msgid format; usg gcos?
	# tailor: add -u for USG GCOS fields
	eval ` defaults $args `		# sets def* variables
	case "$defname" in
	"")	fullname="" ;;		# no full name, leave it off
	*)	fullname=" ($defname)" ;;
	esac

	# badsites="pucc.bitnet!"  # tailor, syntax is "host1!host2!...host3!"
	awk -f $NEWSBIN/inject/defhdrs.awk \
	 defpath="$badsites$defuser" \
	 deffrom="$defuser$defmailsuf$fullname" deforg="$deforg" \
	 defmsgid="$defmsgid" me="$defhostname" $hdrs >$inhdrs
	status=$?
else	status=1
fi

# pad zero-line articles, since old B [ir]news are confused by them
# and the news readers generate zero-line control messages, alas.
if test ! -s $inbody; then
	(echo '';
	 echo This article was probably generated by a buggy news reader.) \
	 >$inbody
fi

# output begins here
# POLICY: don't generate Lines: because it is optional, munged in transit
# by B News to make the count incorrect, and not pulling its weight.
# If you just *have* to generate Lines: headers, uncomment line A and comment
# out line(s) B.
firstline="` sed 1q $inbody `"
# . lines					# NB: reads $inbody # line A
case "$firstline" in				# line B
'')	cat $inhdrs $inbody ;;			# emit the article  # line B
*)	echo | cat $inhdrs - $inbody ;;		# insert blank line # line B
esac						# line B

if test -r $HOME/.signature; then
	# POLICY: chop .sigs at 4 lines
	echo "-- "; sed 4q $HOME/.signature	# glue on first bit of signature
fi
rm -f $rmlist
exit $status
