# Maintainer: Olliver Schinagl <oliver@schinagl.nl>
pkgname=shellcheck
pkgver=0.10.0
pkgrel=1
pkgdesc="a static analysis tool for shell scripts"
url="https://github.com/koalaman/shellcheck"
# limited by ghc
arch="aarch64 x86_64"
license="GPL-3.0"
makedepends="cabal bash ghc libffi-dev pandoc"
subpackages="$pkgname-doc"
source="
	$pkgname-$pkgver.tar.gz::https://github.com/koalaman/shellcheck/archive/v$pkgver.tar.gz
	cabal.config
"
_cabal_home="$srcdir/dist"

cabal_update() {
	msg "Freezing $pkgname dependencies"

	# Resolve deps and generate fresh cabal.config with version constraints.
	HOME="$_cabal_home" cabal update
	(
		cd "$builddir"
		HOME="$_cabal_home" cabal v1-freeze --shadow-installed-packages

		# Add version tag at the first line.
		sed -i "1i--$pkgver" "cabal.config"

		mv "cabal.config" "$startdir/"
	)

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

prepare() {
	default_prepare
	./striptests

	if [ "$(head -n 1 "$srcdir/cabal.config")" != "--$pkgver" ]; then
		die "Requirements file is outdated, run 'abuild cabal_update'"
	fi

	ln -sf "$srcdir/cabal.config" "$builddir/cabal.config"
}

build() {
	# ghc version path
	export PATH="$PATH:/usr/lib/llvm15/bin"
	HOME="$_cabal_home" cabal update
	HOME="$_cabal_home" cabal v1-install \
		--disable-documentation \
		--only-dependencies
	HOME="$_cabal_home" cabal v1-configure \
		--prefix='/usr' \
		--bindir='$prefix/bin' \
		--docdir='$prefix/share/doc' \
		--datadir='$prefix/share' \
		--htmldir='$docdir/html' \
		--libdir='$prefix/lib' \
		--libsubdir="$pkgname" \
		--datasubdir="$pkgname" \
		--dynlibdir="$pkgname" \
		--sysconfdir='/etc' \
		--disable-library-profiling \
		--disable-profiling \
		--disable-shared \
		--enable-executable-stripping \
		--flags='GMP FFI standalone'
	HOME="$_cabal_home" cabal v1-build -j
	./manpage
}

check() {
	_test_script="$(mktemp)"
	{
		echo "#!/bin/sh"
		echo
		echo "exit 0"
	} > "$_test_script"
	trap 'rm "$_test_script"' EXIT
	"$builddir/dist/build/$pkgname/$pkgname" "$_test_script"
	trap - EXIT
	rm "$_test_script"
}

package() {
	HOME="$_cabal_home" cabal v1-copy --destdir="$pkgdir"

	rm -r "$pkgdir/usr/lib/$pkgname"

	mkdir -p "$pkgdir/usr/share/doc/$pkgname"
	mv "$pkgdir/usr/share/doc/LICENSE" "$pkgdir/usr/share/doc/$pkgname"

	install -Dm644 shellcheck.1 -t "$pkgdir"/usr/share/man/man1/
}

sha512sums="
5677ad24602f666bb83358947b740a25fb80afbb991e5fc8436dfa8e970b1e6a828cf7d53fcd24f855764437c6799e194989467a2931e21165d43bc474d57061  shellcheck-0.10.0.tar.gz
9430abf82775ae442bf51f8d0a1827e1d0f4c8a10d5fb631aeafd6604237e531611efa36f49d3cc1b0c3748b7896766ce2f7a52e55d8b930b15fcd1aeeba8250  cabal.config
"
