/*
** 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 (
	"fmt"
	"os"

	"jobarranger2/src/jobarg_server/managers/icon_exec_manager/events"
	"jobarranger2/src/libs/golibs/common"
	"jobarranger2/src/libs/golibs/config_reader/server"
	"jobarranger2/src/libs/golibs/logger/logger"
	"jobarranger2/src/libs/golibs/utils"
)

func main() {
	srcPath := "/var/lib/jobarranger/server/iconexecutionmanager/end/1500000000000000033_1428_20250601171106.json"
	// srcPath := "/var/lib/jobarranger/server/iconexecutionmanager/in/150000000000000020_123_20250617091835.json"
	bytes, err := os.ReadFile(srcPath)
	if err != nil {
		panic(err)
	}

	data := common.Data{
		EventData: bytes,
	}

	// cofig setups
	server.Options.TmpDir = "/var/lib/jobarranger/server/"
	server.Options.UnixSockParentDir = "/usr/local/bin/jobarranger/"

	// main process
	ProcessEventData(data)
}

// empty function to be handled
func StartDaemonWorkers(data common.Data) {}

func ProcessEventData(data common.Data) {
	var err error
	var eventData common.EventData
	var log logger.Logging

	err = utils.UnmarshalEventData(data.EventData, &eventData)
	if err != nil {
		log.JaLog("JAEXEC100002", string(data.EventData), err.Error())
		os.Exit(1)
	}

	switch eventData.Event.Name {
	case common.EventIconReady:
		err = events.EventIconReady(eventData)
	case common.EventIconExecEnd:
		err = events.EventIconEnd(eventData)
	case common.EventIconExecRun:
		err = events.EventIconRun(eventData)
	case common.EventIconAbort:
		err = events.EventIconAbort(eventData)
	case common.EventExecCheckAgent:
		err = events.EventExecCheckAgent(eventData) // Job, Fwait, Reboot
	case common.EventExecCheckLocal:
		err = events.EventExecCheckLocal(eventData) // others icons exclude job,fwait,reboot
	default:
		err = fmt.Errorf("unknown event")
	}

	if err != nil {
		log.JaLog("JAEXEC200003", eventData.Event.Name, err.Error())
		os.Exit(1)
	}
}
