package services

import "testing"

func TestValidateUnit(t *testing.T) {
	valid := []string{"sshd.service", "getty@tty1.service", "foo.bar:baz-1.service", "a_b.timer"}
	for _, u := range valid {
		if err := validateUnit(u); err != nil {
			t.Errorf("validateUnit(%q) = %v, want nil", u, err)
		}
	}

	// Empty, flag-injection, and anything with shell/path metacharacters must
	// be rejected before reaching systemctl.
	invalid := []string{"", "-rf", "--now", "a b", "foo;rm -rf /", "a/b", "naughty$()", "x|y"}
	for _, u := range invalid {
		if err := validateUnit(u); err == nil {
			t.Errorf("validateUnit(%q) = nil, want error", u)
		}
	}
}

// TestIsSelf pins the dispatch that detaches stop/restart-of-self into a
// Setsid subprocess. Both "nadir" and "nadir.service" must match; anything
// else (including substrings) must not, or unrelated services would also get
// detached and bypass the synchronous error path.
func TestIsSelf(t *testing.T) {
	yes := []string{"nadir", "nadir.service"}
	for _, u := range yes {
		if !isSelf(u) {
			t.Errorf("isSelf(%q) = false, want true", u)
		}
	}
	no := []string{"", "sshd.service", "nadir-something.service", "nadir.timer", "not-nadir.service"}
	for _, u := range no {
		if isSelf(u) {
			t.Errorf("isSelf(%q) = true, want false", u)
		}
	}
}
