package cmd

import (
	"fmt"
	"os"
	"runtime"
	"syscall"

	"github.com/spf13/cobra"
)

// ensureRoot checks if the current process is running as root (euid == 0).
// On Linux, service management commands require root privileges.
// If not root, it re-executes the current command with sudo.
// This function only takes effect on Linux; on other platforms it is a no-op.
func ensureRoot(cmd *cobra.Command) {
	if runtime.GOOS != "linux" {
		return
	}
	if os.Geteuid() == 0 {
		return
	}
	// Re-exec with sudo. Preserve PATH so that user-installed runtimes
	// (e.g. via nvm, volta, etc.) are discoverable in the service unit.
	// Preserve AGENTTEAM_CONFIG_DIR so service install targets the same profile
	// directory the foreground daemon command used.
	cmd.PrintErrln("Root privileges required, re-executing with sudo...")
	exe, err := os.Executable()
	if err != nil {
		cmd.PrintErrln(fmt.Sprintf("failed to determine executable path for sudo re-exec: %v\n", err))
		os.Exit(1)
	}
	args, err := sudoReexecArgs(exe, os.Args)
	if err != nil {
		cmd.PrintErrln(fmt.Sprintf("failed to prepare sudo re-exec: %v\n", err))
		os.Exit(1)
	}
	err = syscall.Exec("/usr/bin/sudo", args, os.Environ())
	// If Exec returns, the re-exec failed (shouldn't happen with valid sudo).
	cmd.PrintErrln(fmt.Sprintf("failed to re-exec with sudo: %v\n", err))
	os.Exit(1)
}

func sudoReexecArgs(exe string, argv []string) ([]string, error) {
	if exe == "" {
		return nil, fmt.Errorf("current executable path is empty")
	}
	args := make([]string, 0, len(argv)+2)
	args = append(args, "sudo", "--preserve-env=PATH,AGENTTEAM_CONFIG_DIR", exe)
	if len(argv) > 1 {
		args = append(args, argv[1:]...)
	}
	return args, nil
}
