#!/bin/sh

if [ "$#" -lt 3 ];
then
	echo "Usage: install_lazarus_freebsd.sh <i386/x86_64> <fpc version> <lazarus version> [lazarus source revision]"
	exit 0
fi

case "$1" in
	"i386")
		carch="386"
	;;
	"x86_64")
		carch="x64"
	;;
	*)
		echo "Invalid architecture."
		exit 0
	;;
esac

pkg install gtk2
pkg install gmake
pkg install unzip

cd /tmp

if [ ! -f "/usr/bin/ppc""$carch" ];
then
	DNAME="fpc-""$2"".""$1""-freebsd"
	ANAME="$DNAME""11.tar"
	curl "ftp://ftp.hu.freepascal.org/pub/fpc/dist/""$2""/""$1""-freebsd/""$ANAME" --output "$ANAME"
	if [ ! -f "$ANAME" ];
	then
		echo "Could not download FreePascal binaries."
		exit 0
	fi
	tar -xvf "$ANAME"
	rm "$ANAME"
	cd "$DNAME"
	echo "Install to /usr/ instead of /usr/local/"
	./install.sh
	cd ..
	rm -rf "$DNAME"
fi

cd /tmp

if [ ! -f "/usr/share/fpcsrc/""$2""/Makefile" ];
then
	ANAME="fpc-""$2"".source.zip"
	curl -k "https://netcologne.dl.sourceforge.net/project/freepascal/Source/""$2""/""$ANAME" --output "$ANAME"
	if [ ! -f "$ANAME" ];
	then
		echo "Could not download FreePascal sources."
		exit 0
	fi
	unzip "$ANAME"
	rm "$ANAME"
	SDNAME="fpc-""$2"
	DDNAME="/usr/share/fpcsrc/""$2""/"
	mkdir -p "$DDNAME"
	mv "$SDNAME"/* "$DDNAME"
	rm -rf "$SDNAME"
fi

cd /tmp

if [ ! -f "/usr/local/lazarus/lazarus" ];
then
	mkdir /usr/local/lazarus
	ln -s /usr/local /usr/local/local # WTF
	if [ ! -d "lazarus" ];
	then
		REV=""
		if [ "$4" != "" ];
		then
			REV="-""$4"
		fi
		ANAME="lazarus-""$3""$REV"".zip"
		curl -L -k "https://master.dl.sourceforge.net/project/lazarus/Lazarus%20Zip%20_%20GZip/Lazarus%20""$3""/""$ANAME" --output "$ANAME"
		if [ ! -f "$ANAME" ];
		then
			echo "Could not download Lazarus sources."
			exit 0
		fi
		unzip "$ANAME"
		rm "$ANAME"
	fi
	cd lazarus
	gmake clean bigide
	if [ -f lazarus ];
	then
		gmake install
	fi
	cd ..
	if [ -f "/usr/local/share/lazarus/lazarus" ];
	then
		rm -rf lazarus
	fi
fi
