#!/bin/bash
# 
# Faust project
# version management tool
#

if [ $# -ne 1 ]
then
	echo "Faust version management utility"
	echo "usage: version version_num"
	echo "       version_num format: n.n.n"
	exit 1
fi

function major {
	echo $1 | sed 's/\..*//'
}
function minor {
	echo $1 | sed 's/[0-9]*\.\([0-9]*\)\..*/\1/'
}
function patch {
	echo $1 | sed 's/[0-9]*\.[0-9]*\.\([0-9]*\)/\1/'
}
function winVer {
	echo $1 | sed "s/\./,$2/g"
}
function rcUpdate {
 	sed "s/FILEVERSION[ 	].*/FILEVERSION $2/" $1 | \
 	sed "s/PRODUCTVERSION[ 	].*/PRODUCTVERSION $2/" | \
 	sed "s/VALUE \"FileVersion\"..*/VALUE \"FileVersion\", \"$3\"/" | \
 	sed "s/VALUE \"ProductVersion\"..*/VALUE \"ProductVersion\", \"$3\"/"
}

ROOT=.
VERSION=$1
MAJOR=$(major $VERSION)
MINOR=$(minor $VERSION)
PATCH=$(patch $VERSION)
WINVERS=$(winVer $VERSION)",0"
WINVERS2=$(winVer $VERSION " ")", 0"

if [ -d compiler ]
then
	echo "moving version number to $VERSION"
else
	echo "this script must be called from the Faust project root directory"
	exit 1
fi

MAKEF=$ROOT/Makefile
echo " updating $MAKEF"
sed "s/^version *:= *..*/version := $VERSION/" $MAKEF > TMP$$
mv -f TMP$$ $MAKEF

MAKEF=$ROOT/build/Makefile
echo " updating $MAKEF"
sed "s/^VERSION *:= *..*/VERSION := $VERSION/" $MAKEF > TMP$$
mv -f TMP$$ $MAKEF

CMAKE=$ROOT/build/CMakeLists.txt
echo " updating $CMAKE"
sed "s/set (VERSION[ 	]*[0-9].*)/set (VERSION $VERSION)/" $CMAKE > TMP$$
mv TMP$$ $CMAKE

FAUST=$ROOT/compiler/generator/export.hh
echo " updating $FAUST"
sed "s/FAUSTVERSION[ 	]\".*\"/FAUSTVERSION \"$VERSION\"/" $FAUST > TMP$$
mv -f TMP$$ $FAUST

FAUSTRC=$ROOT/windows/faust.rc
echo " updating $FAUSTRC"
rcUpdate $FAUSTRC $WINVERS "$WINVERS2" > TMP$$
mv -f TMP$$ $FAUSTRC

FAUSTDLLRC=$ROOT/windows/faustdll.rc
echo " updating $FAUSTDLLRC"
rcUpdate $FAUSTRC $WINVERS "$WINVERS2" > TMP$$
mv -f TMP$$ $FAUSTDLLRC

MAN=$ROOT/documentation/man/man-header.txt
echo " updating $MAN"
sed "s/% man(1) Version [ 	]*[0-9].*/% man(1) Version $VERSION (`LC_ALL=C date +%d-%B-%Y`) | Faust man page/" $MAN > TMP$$
mv -f TMP$$ $MAN

COPYING=$ROOT/COPYING.txt
echo " updating $COPYING"
sed "s/FAUST compiler, Version[ 	]*[0-9].*/FAUST compiler, Version $VERSION/" $COPYING > TMP$$
mv -f TMP$$ $COPYING

make man

echo "### You need to recompile Faust for the change to take effect."
exit 0
