/*
** 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 (
	"jobarranger2/src/libs/golibs/common"
	"jobarranger2/src/libs/golibs/logger/logger"
	"jobarranger2/src/libs/golibs/utils"
	"os"
	"path/filepath"
	"strings"
	"time"
)

func retriggerEventFile() {
	fn := "retriggerEventFile"

	logger.WriteLog("JAAGENTRETRIGGER400001", fn, InFolderPath)

	time.Sleep(3 * time.Second) // wait for inotify setup

	// Re-trigger event files
	inEntries, err := os.ReadDir(InFolderPath)
	if err != nil {
		logger.WriteLog("JAAGENTRETRIGGER200001", fn, InFolderPath, err.Error())
		return
	}

	logger.WriteLog("JAAGENTRETRIGGER400002", fn, len(inEntries), InFolderPath)

	for _, inEntry := range inEntries {
		logger.WriteLog("JAAGENTRETRIGGER400003", fn, InFolderPath, inEntry.Name())

		if inEntry.IsDir() {
			logger.WriteLog("JAAGENTRETRIGGER400004", fn, inEntry.Name())
			continue
		}

		entryPath := filepath.Join(InFolderPath, inEntry.Name())

		var destPath string

		if strings.HasSuffix(entryPath, ".json") {
			destPath = entryPath + ".tmp"
		}

		if strings.HasSuffix(entryPath, ".json.tmp") {
			destPath = strings.TrimSuffix(entryPath, ".tmp")
		}

		logger.WriteLog("JAAGENTRETRIGGER400005", fn, entryPath, destPath)

		if err := utils.MoveFileWithLockRetry(entryPath, destPath, common.FileLockRetryCount); err != nil {
			logger.WriteLog("JAAGENTRETRIGGER200002", fn, entryPath, destPath, err.Error())
			continue
		}

		logger.WriteLog("JAAGENTRETRIGGER400006", fn, entryPath, destPath)

		if strings.HasSuffix(destPath, ".json") {
			logger.WriteLog("JAAGENTRETRIGGER400007", fn, destPath)
			continue
		}

		logger.WriteLog("JAAGENTRETRIGGER400008", fn, destPath, entryPath)

		if err := utils.MoveFileWithLockRetry(destPath, entryPath, common.FileLockRetryCount); err != nil {
			logger.WriteLog("JAAGENTRETRIGGER200002", fn, destPath, entryPath, err.Error())
			continue
		}

		logger.WriteLog("JAAGENTRETRIGGER400006", fn, destPath, entryPath)
	}
}
