/*
** Job Arranger for ZABBIX
** Copyright (C) 2025 Daiwa Institute of Research Ltd. All Rights Reserved.
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
**/

package agentutils

import (
	"errors"
	"fmt"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"syscall"
)

// KillProcessIfExists attempts to kill the process with the given PID if it exists.
// It works on both Linux and Windows.
func KillProcessIfExists(pid int) error {
	if pid <= 0 {
		return fmt.Errorf("invalid PID: %d", pid)
	}

	process, err := os.FindProcess(pid)
	if err != nil {
		return fmt.Errorf("failed to find process: %v", err)
	}

	// Platform-specific behavior
	return syscall.Kill(process.Pid, syscall.SIGTERM)
}

// killUnixChildren kills direct child processes of the given parent PID.
func killUnixChildren(ppid int) error {
	procDir := "/proc"

	entries, err := os.ReadDir(procDir)
	if err != nil {
		return fmt.Errorf("failed to read /proc: %w", err)
	}

	for _, entry := range entries {
		if !entry.IsDir() {
			continue
		}

		pid, err := strconv.Atoi(entry.Name())
		if err != nil {
			continue
		}

		// Read /proc/<pid>/stat to get PPID (4th field)
		statPath := filepath.Join(procDir, entry.Name(), "stat")
		data, err := os.ReadFile(statPath)
		if err != nil {
			continue
		}

		fields := strings.Fields(string(data))
		if len(fields) < 5 {
			continue
		}

		ppidField, err := strconv.Atoi(fields[3])
		if err != nil {
			continue
		}

		if ppidField == ppid {
			// Check if process exists and permission to signal
			if err := syscall.Kill(pid, 0); err != nil {
				if errors.Is(err, syscall.ESRCH) {
					continue // process does not exist
				}
				if errors.Is(err, syscall.EPERM) {
					return fmt.Errorf("no permission to signal process %d", pid)
				}
				return fmt.Errorf("failed to check process %d: %v", pid, err)
			}

			// Kill the child process
			if err := syscall.Kill(pid, syscall.SIGTERM); err != nil {
				return fmt.Errorf("failed to kill process %d: %v", pid, err)
			}

		}
	}

	return nil
}

func ProcessExists(pid int) bool {
	if pid <= 0 {
		return false
	}

	err := syscall.Kill(pid, 0)
	if err == nil {
		return true
	}

	if err == syscall.ESRCH {
		return false
	}

	if err == syscall.EPERM {
		return true
	}

	return false
}
