//go:build darwin

package main

import (
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
)

func consoleCmd(vars map[string]string, prof Profile, consoleMsg, tailMsg, tailFile, terminal string) *exec.Cmd {
	envFile, err := os.CreateTemp("", "restray-env-*")
	if err != nil {
		return nil
	}
	for k, v := range vars {
		fmt.Fprintf(envFile, "%s=%s\x00", k, v)
	}
	envFile.Close()

	script, err := os.CreateTemp("", "restray-shell-*.sh")
	if err != nil {
		os.Remove(envFile.Name())
		return nil
	}
	shell := os.Getenv("SHELL")
	if shell == "" {
		shell = "/bin/zsh"
	}
	fmt.Fprintf(script, "#!/bin/sh\n")
	fmt.Fprintf(script, "while IFS='=' read -r -d '' k v; do export \"$k=$v\"; done < %q\n", envFile.Name())
	fmt.Fprintf(script, "rm -f %q\n", envFile.Name())
	if p, _ := findBackend(prof); p != "" {
		fmt.Fprintf(script, "export PATH=%q:\"$PATH\"\n", filepath.Dir(p))
	}
	fmt.Fprintf(script, "clear\n")
	fmt.Fprintf(script, "rm -f %q\n", script.Name())
	fmt.Fprintf(script, "echo '%s'\n", consoleMsg)
	if tailFile != "" {
		fmt.Fprintf(script, "echo '%s'\n", tailMsg)
		fmt.Fprintf(script, "tail -n +1 -f %q &\n", tailFile)
		fmt.Fprintf(script, "TAIL_PID=$!\n")
		fmt.Fprintf(script, "trap 'kill $TAIL_PID 2>/dev/null; wait $TAIL_PID 2>/dev/null' INT\n")
		fmt.Fprintf(script, "wait $TAIL_PID\n")
	}
	fmt.Fprintf(script, "cd %q\n", configDir())
	fmt.Fprintf(script, "exec %s -l\n", shell)
	script.Close()
	os.Chmod(script.Name(), 0700)
	return exec.Command("open", "-a", darwinTerminalApp(terminal), script.Name())
}

func darwinTerminalApp(terminal string) string {
	t := strings.TrimSuffix(strings.ToLower(terminal), ".app")
	switch t {
	case "", "terminal":
		return "Terminal"
	case "iterm", "iterm2":
		return "iTerm"
	case "alacritty":
		return "Alacritty"
	case "kitty":
		return "kitty"
	case "ghostty":
		return "Ghostty"
	case "wezterm":
		return "WezTerm"
	default:
		return terminal
	}
}
