#!/bin/sh

if [ "$#" -lt 3 ];
then
	echo "Usage: install_lazarus_openbsd.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_add bash
pkg_add gtk2mm
pkg_add gmake
pkg_add unzip

cd /tmp

if [ ! -f "/usr/bin/ppc""$carch" ];
then
	DNAME="fpc-""$2"".""$1""-openbsd"
	ANAME="$DNAME"".tar"
	ftp "ftp://ftp.hu.freepascal.org/pub/fpc/dist/""$2""/""$1""-openbsd/""$ANAME" -o "$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"
	ftp "https://netcologne.dl.sourceforge.net/project/freepascal/Source/""$2""/""$ANAME" -o "$ANAME" -S dont
	if [ ! -f "$ANAME" ];
	then
		echo "Could not download FreePascal sources."
		exit 0
	fi
	unzip "$ANAME"
	rm "$ANAME"
	mkdir /usr/share/fpcsrc/
	mv "fpc-""$2" "/usr/share/fpcsrc/""$2"
fi

cd /tmp

if [ ! -f "/usr/local/lazarus/lazarus" ];
then
	mkdir /usr/local/lazarus
	if [ ! -d "lazarus" ];
	then
		REV=""
		if [ "$4" != "" ];
		then
			REV="-""$4"
		fi
		ANAME="lazarus-""$3""$REV"".zip"
		ftp "https://downloads.sourceforge.net/project/lazarus/Lazarus%20Zip%20_%20GZip/Lazarus%20""$3""/""$ANAME" -o "$ANAME" -S dont
		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
