#!/bin/sh

if [ -e Makefile ]; then
	rm Makefile;
fi

#set default options
PYTHON="--python3"
FUSE_GROUP="--fuse-group"

USR_BIN_FILES="backintime backintime-askpass"
FUSE_FILES="sshtools.py encfstools.py"

usage () {
echo "Usage:"
echo "$0 [--python | --python3], [--fuse-group | --no-fuse-group]"
echo ""
echo "--python"
echo "\tuse 'python' to start Python3"
echo "--python3"
echo "\tuse 'python3' to start Python3"
echo "--fuse-group"
echo "\tmake sure user is in group 'fuse' to be able to use fuse-based file-systems"
echo "--no-fuse-group"
echo "\tdo not check for 'fuse' group membership (if not necessary on destination platform)"
}

#get commandline arguments
for arg in $*; do
	case $arg in
		--python | --python3) PYTHON=$arg;;
		--fuse-group | --no-fuse-group) FUSE_GROUP=$arg;;
		--help | -h | *) usage; exit 0;;
	esac
done

#patch python command
#use 'python' or 'python3' to start Python Version 3.x
case $PYTHON in
	--python)   PYVERSION="" ;;
	--python3)  PYVERSION="3";;
esac
sed -e "s/^python3\? /python${PYVERSION} /g" \
    -e "s/^ssh-agent python3\? /ssh-agent python${PYVERSION} /g" \
    -i $USR_BIN_FILES

#patch check for 'fuse' group
#Some distributions require user to be in group 'fuse' to use sshfs and encfs
case $FUSE_GROUP in
	--fuse-group)    CHECKFUSE="True" ;;
	--no-fuse-group) CHECKFUSE="False";;
esac
sed -e "s/CHECK_FUSE_GROUP = \(True\|False\)/CHECK_FUSE_GROUP = ${CHECKFUSE}/" \
    -i $FUSE_FILES

#check languages
mos=""
langs=""
for langfile in `ls po/*.po`; do
	lang=`echo $langfile | cut -d/ -f2 | cut -d. -f1`
	mos="po/$lang.mo $mos"
	langs="$lang $langs"
done

#Start Makefile
printf "LANGS=$langs\n\n" >> Makefile

#add template
cat Makefile.template >> Makefile

#translate
printf "translate: $mos\n\n" >> Makefile

for lang in $langs; do
	printf "po/$lang.mo: po/$lang.po\n" >> Makefile
	printf "\tmsgfmt -o po/$lang.mo po/$lang.po\n\n" >> Makefile
done

#common langs
printf "install_translations:\n" >> Makefile
for lang in $langs; do
	printf "\tinstall -d \$(DEST)/share/locale/$lang/LC_MESSAGES\n" >> Makefile
	printf "\tinstall --mode=644 po/$lang.mo \$(DEST)/share/locale/$lang/LC_MESSAGES/backintime.mo\n" >> Makefile
done
printf "\n" >> Makefile

if [ $(python${PYVERSION} --version 2>&1 | grep -c "^Python 3") -ne 1 ]; then
    printf "Warning: Wrong Python version.\n"
    printf "Please make sure Python 3.x is used by adding '--python' or '--python3'.\n"
    exit 1
fi

printf "All OK. Now run:\n"
printf "    make\n"
printf "    sudo make install\n"

