//go:build linux
// +build linux

// Package platform provides platform-specific utilities for the audit system
package platform

import (
	"fmt"
	"os/exec"
)

// MakeImmutable sets the immutable flag on a file using chattr +i.
// This prevents any modification or deletion of the file, even by root,
// until the flag is cleared.
//
// Requirements:
//   - Linux kernel with immutable flag support
//   - Root access or CAP_LINUX_IMMUTABLE capability
//   - chattr binary available in PATH
//
// Container environments need:
//
//	securityContext:
//	  capabilities:
//	    add: ["CAP_LINUX_IMMUTABLE"]
func MakeImmutable(path string) error {
	cmd := exec.Command("chattr", "+i", path)
	if output, err := cmd.CombinedOutput(); err != nil {
		return fmt.Errorf("chattr +i failed: %w (output: %s)", err, output)
	}
	return nil
}

// MakeAppendOnly sets the append-only flag using chattr +a.
// The file can only be opened in append mode for writing.
func MakeAppendOnly(path string) error {
	cmd := exec.Command("chattr", "+a", path)
	if output, err := cmd.CombinedOutput(); err != nil {
		return fmt.Errorf("chattr +a failed: %w (output: %s)", err, output)
	}
	return nil
}

// ClearImmutable removes the immutable flag from a file
func ClearImmutable(path string) error {
	cmd := exec.Command("chattr", "-i", path)
	if output, err := cmd.CombinedOutput(); err != nil {
		return fmt.Errorf("chattr -i failed: %w (output: %s)", err, output)
	}
	return nil
}

// IsSupported returns true if this platform supports immutable flags
func IsSupported() bool {
	// Check if chattr is available
	_, err := exec.LookPath("chattr")
	return err == nil
}
