package agentutils

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

import (
	"archive/tar"
	"fmt"
	"io"
	"jobarranger2/src/libs/golibs/config_reader/agent"
	"os"
	"path/filepath"
	"time"
)

// ExtractTarToDir extracts a TAR stream from `r` into `targetDir`.
// If `overwrite` is false, it skips existing files.
func ExtractTarToDir(r io.Reader, targetDir string, overwrite bool) error {
	tr := tar.NewReader(r)

	for {
		header, err := tr.Next()
		if err == io.EOF {
			break // End of archive
		}
		if err != nil {
			return fmt.Errorf("tar read error: %w", err)
		}

		headerName := header.Name

		// Encode filename from tar
		encodedFilename, err := EncodeString(headerName, agent.Options.Locale)
		if err != nil {
			return fmt.Errorf("failed to encode received tar filename: %v, error: %v ", encodedFilename, err)
		}

		targetPath := filepath.Join(targetDir, encodedFilename)

		switch header.Typeflag {
		case tar.TypeDir:
			if err := os.MkdirAll(targetPath, os.FileMode(header.Mode)); err != nil {
				return fmt.Errorf("mkdir error: %w", err)
			}

		case tar.TypeReg:
			// Skip existing files if overwrite is false
			if !overwrite {
				if _, err := os.Stat(targetPath); err == nil {
					// File exists
					// Drain the file from the stream to avoid corruption
					if _, err := io.Copy(io.Discard, tr); err != nil {
						return fmt.Errorf("discard skipped file error: %w", err)
					}
					continue
				}
			}

			// Ensure directory exists
			// if err := os.MkdirAll(filepath.Dir(targetPath), 0755); err != nil {
			// 	return fmt.Errorf("mkdir for file: %w", err)
			// }

			outFile, err := os.Create(targetPath)
			if err != nil {
				return fmt.Errorf("file create error: %w", err)
			}

			if _, err := io.Copy(outFile, tr); err != nil {
				outFile.Close()
				return fmt.Errorf("file write error: %w", err)
			}
			outFile.Close()

		default:
		}
	}
	return nil
}

func TarFilesToSocket(w io.Writer, path string) error {
	tw := tar.NewWriter(w)
	defer tw.Close()

	info, err := os.Stat(path)
	if err != nil {
		return fmt.Errorf("stat error: %w", err)
	}
	if info.IsDir() {
		return fmt.Errorf("not a file: %w", err) // skip directories
	}

	f, err := os.Open(path)
	if err != nil {
		return fmt.Errorf("open file error: %w", err)
	}
	defer f.Close()

	// Prepare TAR header
	header, err := tar.FileInfoHeader(info, "")
	if err != nil {
		return fmt.Errorf("header error: %w", err)
	}

	// Convert tar filename to UTF-8
	encodedFilename, err := DecodeString(filepath.Base(path), agent.Options.Locale)
	if err != nil {
		return fmt.Errorf("failed to decode filename: %w", err)
	}

	header.Name = encodedFilename

	// Prepare header format
	header.Format = tar.FormatGNU

	header.AccessTime = time.Time{}
	header.ChangeTime = time.Time{}
	header.ModTime = header.ModTime.Truncate(time.Second)

	if err := tw.WriteHeader(header); err != nil {
		return fmt.Errorf("write header error: %w", err)
	}

	// Write file content
	if _, err := io.Copy(tw, f); err != nil {
		return fmt.Errorf("copy file error: %w", err)
	}
	return nil
}
