package checks

import (
	"github.com/rs/zerolog/log"
	"os/exec"
	"strings"
)

type SystemdConf struct {
	Services []string `yaml:"services"`
	Enabled bool `yaml:"enabled"`
}

type Systemd struct {
	Config SystemdConf
}

func (h Systemd) Execute() (ok bool, data interface{}, err error) {
	if h.Config.Enabled == false {
		return true, nil, nil
	}
	success := true
	servicelist := make(map[string]bool)

	for _, service := range h.Config.Services {
		res, err := h.getStatus(service)
		if err != nil {
			return false, nil, err
		}
		if res == false {
			success = false
		}
		servicelist[service] = res
	}

	return success, servicelist,nil
}

func (h Systemd) Name() string {
	return "SystemdStatus"
}

func (h Systemd) getStatus(name string) (bool, error) {
	cmd := exec.Command("systemctl", "check", name)
	out, err := cmd.CombinedOutput()
	if err != nil {
		log.Debug().Err(err).Msg("Error in systemd communication")
		if exitErr, ok := err.(*exec.ExitError); ok {
			if exitErr.ExitCode() == 3 {
				return false, nil
			}
		}
		return false, err
	}


	s := string(out)
	s = strings.Trim(s, "\n")
	if s == "active" {
		return true, nil
	}
	return false, nil
}
