#!/bin/bash

. ${TOOLKIT}-functions.sh

repos=`jtconf install.mirror_downloaded` || exit_missing_define install.mirror_downloaded
mono_version=`jtconf mono.version`	|| exit_missing_define mono.version



SRCDIR="/usr/src"
INSTALLDIR="/opt/mono$mono_version"


compile_source()
{
	local package=$1
	local release=$2
	local patches=${3:-""}

	local sourcefile="$package-$release.tar.bz2"
	local srcdir="$SRCDIR/$package-$release"
	local here=`pwd`
	
	[ -d $srcdir ] || {
		cd `dirname $srcdir` || exit $?
		[ -f $sourcefile ] || {
			wgetfile $repos/mono/$sourcefile || exit $?
		}
		echo -en "\n extracting files to $srcdir ... "
		tar xfpj $sourcefile || exit $?
		echo "done"
	}
	[ -d $srcdir ] || {
		echo "something goes wrong, source dir $srcdir not found"
		exit 1
	}

	cd $srcdir

	[ "$patches" ] && {
		[ -f $here/$patches ] || {
			echo "error, patchfile $here/$patches not found!"
			exit 1
		}
		echo -e "\n appling paches $patches ....\n"
		tar xvfpj $here/$patches || exit $?
	}

	echo -e "\n compiling $package in $srcdir ... \n"

	./configure --prefix=$INSTALLDIR || exit $?
	make || exit $?
	make install || exit $?
	cd $here
}


# fixes crappy perms (doesn't anyone known about this?)
#
fix_perms()
{
	chmod a+r -R /opt/mono$mono_version || return $?
	find /opt/mono$mono_version -type d -print0 | xargs -0 chmod a+x || return $?
}



# link to /usr/bin only if not exists or is already a symlink (if not, we can
# break existing mono installation)
#
fix_link()
{
	[ -L /usr/bin/mono -o ! -e /usr/bin/mono ] && {
		cd /usr/bin
		rm -f mono
		echo "  linking /usr/bin/mono$mono_version -> /usr/bin/mono"
		ln -s mono$mono_version mono || return $?
	}
	return 0
}



[ -x /usr/bin/mono$mono_version -a -d $INSTALLDIR ] && {
	fix_perms || exit $?
	fix_link || exit $?
	echo "  mono$mono_version already installed"
	exit 0	# nothing to do
}

# try pre-compiled runtime, if not, try to compile
#
binfile="mono-bin-${mono_version}_$DISTRIB_CODENAME.tar.bz2"

if wgetfile $repos/mono/$binfile
then
	here=`pwd`
	cd /opt
	echo -n "  extracting mono-$mono_version in /opt ..."
	tar xfj $here/$binfile || exit $?
	echo "ok"
	cd $here
	rm -f $binfile
else
	# get latest release infos
	#
	libgdiplus_releas=
	mono_release=
	mono_patches=
	wgetfile $repos/mono/latest_releases	|| exit $?
	set -e
	. latest_releases
	set +e
	rm -f latest_releases

	# is installed the custom release?
	#
	[ -f $INSTALLDIR/lib/libgdiplus.so.0 ] || {
		compile_source libgdiplus $libgdiplus_release || exit $?
	}
	[ -f $INSTALLDIR/bin/mono ] || {
		compile_source mono $mono_release $mono_patches || exit $?
	}
fi

fix_perms || exit $?
fix_link || exit $?

exit 0
