package rosa

import (
	"path"
	"strings"

	"hakurei.app/internal/pkg"
)

func (t Toolchain) newGit() (pkg.Artifact, string) {
	const (
		version  = "2.54.0"
		checksum = "7vGKtFOJGqY8DO4e8UMRax7dLgImXKQz5MMalec6MlgYrsarffSJjgOughwRFpSH"
	)
	return t.NewPackage("git", version, newTar(
		"https://www.kernel.org/pub/software/scm/git/"+
			"git-"+version+".tar.gz",
		checksum,
		pkg.TarGzip,
	), &PackageAttr{
		ScriptEarly: `
ln -s ../../system/bin/perl /usr/bin/ || true

# test suite assumes apache
rm -f /system/bin/httpd
`,

		// uses source tree as scratch space
		EnterSource: true,
	}, &MakeHelper{
		InPlace:  true,
		Generate: "make configure",
		ScriptMakeEarly: `
function disable_test {
	local test=$1 pattern=${2:-''}
	if [ $# -eq 1 ]; then
		rm "t/${test}.sh"
	else
		sed -i "t/${test}.sh" \
			-e "/^\s*test_expect_.*$pattern/,/^\s*' *\$/{s/^/: #/}"
	fi
}

disable_test t1800-hook
disable_test t5319-multi-pack-index
disable_test t1305-config-include
disable_test t3900-i18n-commit
disable_test t3507-cherry-pick-conflict
disable_test t4201-shortlog
disable_test t5303-pack-corruption-resilience
disable_test t4301-merge-tree-write-tree
disable_test t8005-blame-i18n
disable_test t9350-fast-export
disable_test t9300-fast-import
disable_test t0211-trace2-perf
disable_test t1517-outside-repo
disable_test t2200-add-update
disable_test t0027-auto-crlf
disable_test t7513-interpret-trailers
disable_test t7703-repack-geometric
disable_test t7002-mv-sparse-checkout
disable_test t1451-fsck-buffer
disable_test t4104-apply-boundary
disable_test t4200-rerere
disable_test t5515-fetch-merge-logic
`,
		Check: []string{
			"-C t",
			`GIT_PROVE_OPTS="--jobs 32 --failures"`,
			"prove",
		},
		Install: `make \
	` + jobsFlagE + ` \
	DESTDIR=/work \
	NO_INSTALL_HARDLINKS=1 \
	install`,
	},
		// test suite hangs on mksh
		Bash,

		Diffutils,
		Autoconf,
		Gettext,

		Zlib,
		Curl,
		Libexpat,
	), version
}
func init() {
	artifactsM[Git] = Metadata{
		f: Toolchain.newGit,

		Name:        "git",
		Description: "distributed version control system",
		Website:     "https://www.git-scm.com/",

		Dependencies: P{
			Zlib,
			Curl,
			Libexpat,
		},

		ID: 5350,
	}
}

// NewViaGit returns a [pkg.Artifact] for cloning a git repository.
func (t Toolchain) NewViaGit(
	url, rev string,
	checksum pkg.Checksum,
) pkg.Artifact {
	return t.New(strings.TrimSuffix(
		path.Base(url),
		".git",
	)+"-src-"+path.Base(rev), THostNet, t.AppendPresets(nil,
		NSSCACert,
		Git,
	), &checksum, nil, `
git \
	-c advice.detachedHead=false \
	clone \
	--depth=1 \
	--revision=`+rev+` \
	--shallow-submodules \
	--recurse-submodules \
	`+url+` \
	/work
rm -rf /work/.git
`, resolvconf())
}

// newTagRemote is a helper around NewViaGit for a tag on a git remote.
func (t Toolchain) newTagRemote(url, tag, checksum string) pkg.Artifact {
	return t.NewViaGit(url, "refs/tags/"+tag, mustDecode(checksum))
}
