// SPDX-License-Identifier: GPL-3.0-or-later

//go:build linux

package service

import (
	"os"
	"path/filepath"
)

// detectInitSystem identifies which init system is running on this Linux host.
func detectInitSystem() InitSystem {
	// Check for systemd first (most common on modern distros).
	// PID 1 is systemd if /run/systemd/system exists.
	if _, err := os.Stat("/run/systemd/system"); err == nil {
		return InitSystemd
	}
	// Fallback: check for systemctl binary.
	if commandExists("systemctl") {
		return InitSystemd
	}

	// Check for OpenRC.
	if commandExists("rc-service") || commandExists("openrc") {
		return InitOpenRC
	}
	// Alternative OpenRC detection: /etc/init.d/ exists and no systemd.
	if _, err := os.Stat("/etc/init.d"); err == nil {
		// Could also be SysVinit — check for openrc marker.
		if _, err2 := os.Stat("/sbin/openrc"); err2 == nil {
			return InitOpenRC
		}
		// Check for a typical OpenRC directory.
		if entries, err2 := os.ReadDir(filepath.Join("/etc", "runlevels")); err2 == nil && len(entries) > 0 {
			return InitOpenRC
		}
	}

	return InitUnknown
}

// newManager creates the appropriate Manager for the given init system.
func newManager(initSys InitSystem) (Manager, error) {
	switch initSys {
	case InitSystemd:
		return &systemdManager{}, nil
	case InitOpenRC:
		return &openrcManager{}, nil
	default:
		return nil, ErrUnsupportedInitSystem
	}
}
