#!/bin/bash
#
# test/sdist: tests the package generated by "cabal sdist".
#
# Copyright (c) 2015-2025 Rudy Matela.
# Distributed under the 3-Clause BSD licence.

set -xe

export LC_ALL=C  # consistent sort

pkgver=` cat *.cabal | grep "^version:" | sed -e "s/version: *//"`
pkgname=`cat *.cabal | grep "^name:"    | sed -e "s/name: *//"`
pkgbase=$pkgname-$pkgver

cabal sdist

# Try to find the package generated by cabal.
pkg=`find dist* -name $pkgbase.tar.gz`
[ -f "$pkg" ]
# If the script fails here, either:
#   * no package was generated
#   * there are packages in both dist and dist-newstyle folders.

tmp=`mktemp -d /tmp/test-sdist-XXXXXXXXXX`

# Test if our file is compatible with case-insensitive filesystems.
tar -tf $pkg | sort --ignore-case          > $tmp/ls-cabal-i
tar -tf $pkg | sort --ignore-case --unique > $tmp/ls-cabal-iu
diff -rud $tmp/ls-cabal-i $tmp/ls-cabal-iu

# Check if we have a clone of the repo and git is available
# The check that we can run git ls-files is needed to avoid:
# fatal: detected dubious ownership in repository at '/__w/.../hello-haskell'
# on CI.
if [ -d .git ] && git --version && git ls-files >/dev/null
then
	# Test if files included by cabal are the same as files tracked in git.
	git ls-files                                         | sort > $tmp/ls-git
	tar -tf $pkg | grep -v "/$" | sed -e "s,$pkgbase/,," | sort > $tmp/ls-cabal
	diff -rud $tmp/ls-git $tmp/ls-cabal
fi

rm -r $tmp
