package rosa

var (
	_python       = H("python")
	_pythonPyTest = H("python-pytest")
)

// PipHelper installs python packages from source using pip.
type PipHelper struct {
	// Path elements joined with source.
	Append []string
	// Whether to omit --no-build-isolation.
	BuildIsolation bool
	// Whether to enter source after install.
	EnterSource bool
	// Whether to install to build environment after install.
	Install bool
	// Whether to skip running tests.
	SkipCheck bool
	// Replaces pytest if non-empty.
	Check string
	// Runs after install.
	Script string
}

var _ Helper = new(PipHelper)

// extra returns python, or pytest if defaults are assumed.
func (attr *PipHelper) extra() P {
	if attr == nil || (!attr.SkipCheck && attr.Check == "") {
		return P{_pythonPyTest}
	}
	return P{_python}
}

// wantsChmod returns true.
func (*PipHelper) wantsChmod() bool { return true }

// wantsWrite is equivalent to wantsChmod.
func (attr *PipHelper) wantsWrite() bool { return attr.wantsChmod() }

// scriptEarly is a noop.
func (*PipHelper) scriptEarly() string { return "" }

// wantsDir requests a new directory in TMPDIR.
func (*PipHelper) wantsDir() (string, bool) { return `"$(mktemp -d)"`, false }

// script generates the pip3 install command.
func (attr *PipHelper) script(t Toolchain, name string) string {
	if attr == nil {
		attr = new(PipHelper)
	}
	sourcePath := AbsUsrSrc.Append(name).Append(attr.Append...)

	var extra string
	if !attr.BuildIsolation {
		extra += `
	--no-build-isolation \`
	}

	var script string
	if attr.Install {
		script += `pip3 install \
	--no-index \
	--prefix=/system \
	--no-build-isolation \
	'` + sourcePath.String() + `'
`
	}
	if attr.EnterSource {
		script += "cd '/usr/src/" + name + "'\n"
	}
	if !attr.SkipCheck && t.opts&OptSkipCheck == 0 {
		if attr.Check == "" {
			// some test suites fall apart when ran out-of-tree
			script += "(cd '" + sourcePath.String() + "' && pytest)\n"
		} else {
			script += attr.Check
		}
	}
	script += attr.Script

	return `
pip3 install \
	--no-index \
	--prefix=/system \
	--root=/work \` + extra + `
	'` + sourcePath.String() + `'
` + script
}
