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

import (
	"encoding/json"
	"fmt"
	"net"
	"os"

	"jobarranger2/src/jobarg_agent/managers/agent_manager/agentutils"
	"jobarranger2/src/libs/golibs/common"
	"jobarranger2/src/libs/golibs/forker"
	"jobarranger2/src/libs/golibs/logger/logger"
)

func handleAgentFileCopy(eventData *common.EventData, netConn *common.NetConnection) error {
	funcName := "handleAgentFileCopy"

	tcpConn := netConn.Conn.(*net.TCPConn)
	file, err := tcpConn.File()
	if err != nil {
		return fmt.Errorf("failed to convert netconn to fd: %v", err)
	}

	bytes, err := json.Marshal(eventData)
	if err != nil {
		return fmt.Errorf("failed to marshal event data: %v", err)
	}

	var agentData common.AgentDataW
	agentData.EventData = bytes

	agentDataBytes, err := json.Marshal(agentData)
	if err != nil {
		return fmt.Errorf("failed to marshal agent data: %v", err)
	}

	proc := forker.New(forker.ProcessData{
		ExecPath: FCopyClientExecPath,
		ExecParams: []string{
			"-config-file-path", common.ConfigFilePath,
		},
		StdinBytes: agentDataBytes,

		ExtraFiles: []*os.File{file},

		Detached: true,
	})

	cmd, err := proc.StartNewProcess()
	if err != nil {
		logger.WriteLog("JAAGENTMNG200022", funcName, FCopyClientExecPath, err)
		msg := fmt.Sprintf("failed to start fcopy client process [%s]: %v", FCopyClientExecPath, err)
		eventData.TCPMessage.Data = common.ResponseData{
			Result:  common.JA_JOBRESULT_FAIL,
			Message: &msg,
		}

		return agentutils.SendToServer(eventData, netConn)
	}

	logger.WriteLog("JAAGENTMNG400019", funcName, cmd.Process.Pid)

	return nil

}
