#!/bin/bash

set -e

export LC_ALL=C

definefile="$1"
define="$2"
release="$3"
srcdir="$4"
infile="$5"

definedata="$(cat $definefile | grep "^\#define $define" | sed -e 's/.*'$define' //')"

realinfile="$(ls $srcdir/$infile.*{py,pl,sh} 2>/dev/null || true)"

[ -z "$realinfile" ] && exit 1

interpreter="$(cat $realinfile | head -n 1 | awk -F "/" '{print $NF}')"
interpreter="$(echo $interpreter)"

case "$interpreter" in
	perl)
		start="\$"
		end=";"
	;;
	*)
		start=""
		end=""
	;;
esac

awk "{print}(\$1 ~ /#BEGIN_VERSION_GENERATION/){exit 0}" $realinfile
echo ${start}RELEASE_VERSION=\"${release}\"${end}
echo ${start}BUILD_DATE=\"\(built $(date)\)\"${end}
if awk -v p=0 "(\$1 ~ /#BEGIN_VERSION_GENERATION/){p = 1} (\$1 ~ /#END_VERSION_GENERATION/){p = 0} {if(p==1)print}" $realinfile | \
		grep -q REDHAT_COPYRIGHT; then
	echo ${start}REDHAT_COPYRIGHT=${definedata}${end}
fi
awk -v p=0 "(\$1 ~ /#END_VERSION_GENERATION/){p = 1} {if(p==1)print}" $realinfile

exit 0
