# Contributor: gay <gay@disroot.org>
# Maintainer: Celeste <cielesti@protonmail.com>
maintainer="Celeste <cielesti@protonmail.com>"
pkgname=stack
pkgver=3.1.1
pkgrel=0
pkgdesc="The Haskell Tool Stack"
url="https://haskellstack.org/"
arch="aarch64 x86_64" # limited by ghc
license="BSD-3-Clause"
makedepends="
	cabal
	ghc
	gmp-dev
	sqlite-dev
	uusi
	zlib-dev
	"
checkdepends="ncurses-dev"
subpackages="
	$pkgname-bash-completion
	$pkgname-fish-completion
	$pkgname-zsh-completion
	"
source="https://hackage.haskell.org/package/stack-$pkgver/stack-$pkgver.tar.gz
	cabal.project.freeze
	"

export CABAL_DIR="${CABAL_DIR:-"$srcdir/cabal"}"

cabal_relax() {
	# Following what Homebrew does
	cat > "$builddir"/cabal.project <<-'END'
		packages: .
	END

	uusi -u directory -u filepath "$builddir"/$pkgname.cabal
}

cabal_update() {
	local repo="hackage.haskell.org"

	# Default config uses HTTP, change it to HTTPS.
	[ -f "$CABAL_DIR"/config ] || {
		cabal user-config init
		cabal user-config update -a \
			"repository $repo {url: https://$repo/}"
	}

	cd "$startdir"
	[ -d "$builddir" ] || abuild unpack
	msg "Freezing $pkgname dependencies"

	# Resolve deps and generate fresh cabal.project.freeze with version constraints.
	(
		cd "$builddir" || {
			error 'Is $builddir set correctly?'
			return 1
		}
		cabal_relax

		cabal v2-update
		cabal v2-freeze --shadow-installed-packages

		mv -v cabal.project.freeze "$startdir"/
	)

	if ! abuild checksum; then
		die "Failed to update checksum, run 'abuild checksum' manually"
	fi
}

prepare() {
	cabal_relax
	default_prepare

	ln -svf "$srcdir"/cabal.project.freeze "$builddir"/
}

build() {
	cabal v2-update
	cabal v2-build stack:exes \
		--jobs=${JOBS:-1} \
		--prefix=/usr \
		--docdir=/usr/share/doc/$pkgname \
		--sysconfdir=/etc \
		--enable-relocatable
}

check() {
	cabal test
}

package() {
	cd dist-newstyle/build/*-linux/ghc-*/$pkgname-$pkgver/build/$pkgname
	install -Dvm755 $pkgname -t "$pkgdir"/usr/bin/

	./stack --bash-completion-script stack | install -Dm644 /dev/stdin \
		"$pkgdir"/usr/share/bash-completion/completions/$pkgname
	./stack --fish-completion-script stack | install -Dm644 /dev/stdin \
		"$pkgdir"/usr/share/fish/vendor_completions.d/$pkgname.fish
	./stack --zsh-completion-script stack | install -Dm644 /dev/stdin \
		"$pkgdir"/usr/share/zsh/site-functions/_$pkgname
}

sha512sums="
2990996e08297d2f4eb5f06750db1130e785e26e8c5a7302a533b4ded278793bd7be3bb2532bcd76270105b41f0dba2eceaaf2887142b5e315a6565b0b5a6cee  stack-3.1.1.tar.gz
23b0c85570e579ca8636e1a9cbd65f6d4c672ae3faa130531d5b411819bf4ebb952057b78907898c91a29a9c4a463bc707e7ce8620588e1b92212e9f2e0e0209  cabal.project.freeze
"
