//go:build !darwin && !windows

package main

import (
	"fmt"
	"log"
	"os"
	"os/exec"
)

func findTerminal() string {
	if t := os.Getenv("TERMINAL"); t != "" {
		return t
	}
	for _, t := range []string{"x-terminal-emulator", "kgx", "gnome-terminal", "konsole", "xfce4-terminal", "alacritty", "kitty", "foot", "wezterm", "ghostty", "xterm"} {
		if p, err := exec.LookPath(t); err == nil {
			return p
		}
	}
	return ""
}

func consoleCmd(vars map[string]string, prof Profile, consoleMsg, tailMsg, tailFile, terminal string) *exec.Cmd {
	shell := os.Getenv("SHELL")
	if shell == "" {
		shell = "/bin/sh"
	}
	term := terminal
	if term == "" {
		term = findTerminal()
	}
	if term == "" {
		log.Print("console: no terminal emulator found")
		return nil
	}
	var script string
	if tailFile != "" {
		script = fmt.Sprintf("cd %q; clear; echo '%s'; echo '%s'; tail -n +1 -f %q; exec %s", configDir(), consoleMsg, tailMsg, tailFile, shell)
	} else {
		script = fmt.Sprintf("cd %q; clear; echo '%s'; exec %s", configDir(), consoleMsg, shell)
	}
	cmd := exec.Command(term, "-e", shell, "-c", script)
	env := os.Environ()
	for k, v := range vars {
		env = append(env, k+"="+v)
	}
	cmd.Env = envWithBackendPath(env, prof)
	return cmd
}
