#!/bin/bash

set -e

# Set variables
# in - input man page (something_foo.3.in)
# out - output file (something_foo.3)
# common - common ipc error file

in="$1"
out="$2"
common="$3"

# make sure to trap on error and ctrl+c
# so we can cleanup our temporary files
# and provide error back to Makefile
cleanup() {
	rm -f "$out"-t "$out"
}

trap "cleanup" ABRT
trap "cleanup" QUIT
trap "cleanup" TERM
trap "cleanup" INT
trap "cleanup" ERR

# Determine build date in man page format YYYY-MM-DD
date="$(LC_ALL=C date "+%F")"

# do the hack.. it looks ugly but it works fine

# remove temporary file
rm -f "$out"-t

# insert the $common ipc error file in the man page
if grep -q @COMMONIPCERRORS@ "$in"; then
	awk "{print}(\$1 ~ /@COMMONIPCERRORS@/){exit 0}" "$in" > "$out"-t
	cat "$common" >> "$out"-t
	awk -v p=0 "(\$1 ~ /@COMMONIPCERRORS@/){p = 1} {if(p==1)print}" "$in" >> "$out"-t
else
	cp "$in" "$out"-t
fi

# substitute BUILDDATE with precalculated date
# and remove COMMONIPCERRORS tag from above
sed -i \
	-e 's#@BUILDDATE@#'$date'#g' \
	-e 's#@COMMONIPCERRORS@##g' \
	"$out"-t

# move in place as requested
mv "$out"-t "$out"
