#! /bin/sh
# Run this to generate all the initial makefiles, etc.
#
# Copyright (C) 2003 g10 Code GmbH
#
# This file is free software; as a special exception the author gives
# unlimited permission to copy and/or distribute it, with or without
# modifications, as long as this notice is preserved.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY, to the extent permitted by law; without even the
# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

win_rel=1
git_revision=""
tsdir="$(readlink -f $(dirname $0))"

claws_full_ver=$(grep -E "^claws_mail," packages/packages.current | cut -f 2 -d ,)
claws_base_ver=$(echo ${claws_full_ver} | cut -f 1 -d -)

claws_type=$(grep -E "^claws_mail," packages/packages.current | cut -f 3 -d ,)
if [ "x${claws_type}" = "xgit" ]; then
	echo "Building a git snapshot of Claws Mail."
	git_revision="git$(echo ${claws_full_ver} | cut -f 2 -d -)"
	win_rel=99
fi

printf "%s\n" "${claws_base_ver}" > ${tsdir}/VERSION
printf "%s\n" "${win_rel}" >> ${tsdir}/VERSION
printf "%s\n" "${git_revision}" >> ${tsdir}/VERSION

# Reject unsafe characters in $tsdir and cwd.  We consider spaces as unsafe
# because it is too easy to get scripts wrong in this regard.
if [ "$tsdir" != "$(echo $tsdir | tr -d -c '[A-Za-z0-9/\-_.]')" ]; then
	printf "unsafe source directory: \"%s\"\n" "$tsdir"
	exit 1
elif [ "$(pwd)" != "$(pwd | tr -d -c '[A-Za-z0-9/\-_.]')" ]; then
	printf "unsafe working directory: \"%s\"\n" "$(pwd)"
	exit 1
fi

# autom4te.cache may contain outdated version number
rm -rf autom4te.cache
echo "Running aclocal -I m4 -Wall..."
if ! aclocal -I m4 -Wall; then exit $?; fi
echo "Running autoconf -Wall..."
if ! autoconf -Wall; then exit $?; fi
echo "Running autoheader -Wall..."
if ! autoheader -Wall; then exit $?; fi
echo "Running automake --gnu -Wall -Wno-portability --add-missing --copy ..."
if ! automake --gnu -Wall -Wno-portability --add-missing --copy; then exit $?; fi

# Convenience option to use certain configure options for some hosts.
case "$1" in
	--build-w32)
		host_triplet="i686-w64-mingw32"
		shift
		;;
	--build-w64)
		host_triplet="x86_64-w64-mingw32"
		shift
		;;
	"")
		host_triplet="x86_64-w64-mingw32"
		;;
	*)
		echo "**Error**: invalid build option $1" >&2
		exit 1
		;;
esac

if [ -f "$tsdir/config.log" ]; then
	if ! head $tsdir/config.log | grep "$host_triplet" >/dev/null; then
		echo "Please run a 'make distclean' first" >&2
		exit 1
	fi
fi

build=$($tsdir/build-aux/config.guess)

echo "Running configure --host=${host_triplet} --build=${build} --enable-maintainer-mode $@"
if ! $tsdir/configure --host=${host_triplet} --build=${build} --enable-maintainer-mode "$@"; then exit $?; fi

printf "You may now run make.\n"
