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

import (
	"jobarranger2/src/libs/golibs/common"
	"os"
	"path/filepath"
	"strings"
)

func CreateUniqueFile(folderPath, fileName string) error {
	// Ensure the folder exists
	if err := os.MkdirAll(folderPath, common.FilePermission); err != nil {
		return err
	}

	fullPath := filepath.Join(folderPath, fileName)

	// O_EXCL + O_CREATE => error if file already exists
	file, err := os.OpenFile(fullPath, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644)
	if err != nil {
		return err
	}
	defer file.Close()

	return nil
}

func DeleteFilesUnderFolder(folderPath, ext string) error {
	if _, err := os.Stat(folderPath); err != nil {
		if os.IsNotExist(err) {
			return nil
		}
		return err
	}
	return filepath.WalkDir(folderPath, func(path string, d os.DirEntry, err error) error {
		if err != nil {
			return err
		}

		if d.IsDir() {
			return nil
		}

		if ext == "*" || strings.HasSuffix(d.Name(), ext) {
			return os.Remove(path)
		}

		return nil
	})
}
