/*
** 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 utils

import (
	"fmt"
	"os"
	"path/filepath"
	"strings"
)

// ProcessInfo holds basic info about a process
type ProcessInfo struct {
	PID     int
	Name    string // binary name
	Cmdline string // full command line
}

// GetProcessInfo checks if a process exists and returns its name and cmdline
func GetProcessInfo(pid int) (*ProcessInfo, error) {
	procPath := filepath.Join("/proc", fmt.Sprint(pid))

	// Check if /proc/<pid> exists
	if _, err := os.Stat(procPath); err != nil {
		if os.IsNotExist(err) {
			return nil, nil
		}

		return nil, fmt.Errorf("failed to check process %d: %v", pid, err)
	}

	// Read process name
	commPath := filepath.Join(procPath, "comm")
	nameBytes, err := os.ReadFile(commPath)
	if err != nil {
		return nil, fmt.Errorf("cannot read process comm: %w", err)
	}
	name := strings.TrimSpace(string(nameBytes))

	// Read full command line
	cmdPath := filepath.Join(procPath, "cmdline")
	cmdBytes, err := os.ReadFile(cmdPath)
	if err != nil {
		return nil, fmt.Errorf("cannot read process cmdline: %w", err)
	}
	cmdline := strings.ReplaceAll(string(cmdBytes), "\x00", " ")
	cmdline = strings.TrimSpace(cmdline)

	return &ProcessInfo{
		PID:     pid,
		Name:    name,
		Cmdline: cmdline,
	}, nil
}
