#!/bin/bash
# Bootstraps from an empty cabal (plus apt-get build-dep git-annex)
# to all the necessary haskell packages being installed, with the
# necessary patches to work on architectures that lack template haskell.
#
# Note that the newest version of packages are installed. 
# It attempts to reuse patches for older versions, but 
# new versions of packages often break cross-compilation by adding TH, 
# etc
#
# Future work: Convert to using the method used here:
# https://github.com/kaoskorobase/ghc-ios-cabal-scripts/

set -e

if [ ! -d haskell-patches ]; then
	cd standalone/linux
fi

cabalopts="$@"

cabalinstall () {
	echo cabal install -j1 "$@" "$cabalopts"
	eval cabal install -j1 "$@" "$cabalopts"
}

patched () {
	pkg=$1
	shift 1
	cabal unpack $pkg$1
	shift 1
	cd $pkg*
	git init
	git config user.name dummy
	git config user.email dummy@example.com
	git add .
	git commit -m "pre-patched state of $pkg"
	for patch in ../../haskell-patches/${pkg}_* ../../../no-th/haskell-patches/${pkg}_*; do
		if [ -e "$patch" ]; then
			echo trying $patch
			if ! patch -p1 < $patch; then
				echo "failed to apply $patch"
				echo "please resolve this, replace the patch with a new version, and exit the subshell to continue"
				$SHELL
			fi
		fi
	done
	cabalinstall "$@"
	rm -rf $pkg*
	cd ..
}

installgitannexdeps () {
	pushd ../..
	echo "cabal install QuickCheck -f-templateHaskell"
	cabal install QuickCheck -f-templateHaskell
	echo cabal install --only-dependencies "$@"
	cabal install --only-dependencies "$@"
	popd
}

install_pkgs () {
	rm -rf tmp
	mkdir tmp
	cd tmp

	patched network
	patched wai-app-static
	patched vector
	patched aeson
	patched shakespeare
	patched yesod-routes
	patched monad-logger
	patched skein
	patched yesod-core
	patched persistent
	patched persistent-template
	# Newer versions of file-embed cause ghc -ddump-splices
	# to output invalid character codes.
	# Note that the system generating the splices should also
	# use this version of file-embed.
	patched file-embed -0.0.6
	patched process-conduit
	patched yesod-static
	patched yesod-persistent
	patched yesod-form
	patched yesod-auth
	patched yesod
	patched generic-deriving
	patched profunctors
	patched reflection
	patched lens
	patched xml-hamlet
	patched DAV

	cd ..

	installgitannexdeps
}

cabal update

# Some packages fail to install in a non unicode locale.
LANG=C.UTF-8
export LANG

install_pkgs
