package main

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

var (
	base    = filepath.Join(os.TempDir(), "tailors-"+strconv.Itoa(os.Getuid()))
	pealAt  = base + ".wav"
	pidFile = base + ".pid"
)

// players in the order they are tried, after $TAILORS_PLAYER.
var players = [][]string{
	{"afplay"},
	{"paplay"},
	{"aplay", "-q"},
	{"ffplay", "-nodisp", "-autoexit", "-loglevel", "quiet"},
	{"play", "-q"},
}

// findPlayer returns the first player found, its arguments, and nil if none is.
func findPlayer() []string {
	list := players
	if p := strings.Fields(os.Getenv("TAILORS_PLAYER")); len(p) > 0 {
		list = append([][]string{p}, players...)
	}
	for _, p := range list {
		if path, err := exec.LookPath(p[0]); err == nil {
			return append([]string{path}, p[1:]...)
		}
	}
	return nil
}

// writeFresh writes a new file at path, never through whatever stood there.
func writeFresh(path string, data []byte) error {
	os.Remove(path)
	f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644)
	if err != nil {
		return err
	}
	_, err = f.Write(data)
	if cerr := f.Close(); err == nil {
		err = cerr
	}
	return err
}

// stopBell ends the bell still ringing, if the pidfile still names it.
// It reports whether one was stopped.
func stopBell() bool {
	b, err := os.ReadFile(pidFile)
	if err != nil {
		return false
	}
	var pid int
	var name string
	if n, _ := fmt.Sscan(string(b), &pid, &name); n != 2 || pid <= 1 {
		return false
	}
	out, err := exec.Command("/bin/ps", "-o", "comm=", "-p", strconv.Itoa(pid)).Output()
	if err != nil {
		return false
	}
	// Linux cuts comm to 15 bytes; macOS prints the whole path.
	if cut(filepath.Base(strings.TrimSpace(string(out)))) != cut(name) {
		return false
	}
	if syscall.Kill(-pid, syscall.SIGTERM) != nil {
		return false
	}
	os.Remove(pidFile)
	return true
}

func cut(s string) string { return s[:min(15, len(s))] }

// ring stops the bell still ringing, puts the new peal in place and starts the
// player detached: its own session, /dev/null for its input and output, never
// waited for.
// It reports false when no player was found; the peal is in place either way.
func ring(tmp string) (bool, error) {
	stopBell()
	if err := os.Rename(tmp, pealAt); err != nil {
		return false, err
	}
	p := findPlayer()
	if p == nil {
		return false, nil
	}
	null, err := os.OpenFile(os.DevNull, os.O_RDWR, 0)
	if err != nil {
		return true, err
	}
	defer null.Close()
	cmd := exec.Command(p[0], append(p[1:], pealAt)...)
	cmd.Stdin, cmd.Stdout, cmd.Stderr = null, null, null
	cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
	if err := cmd.Start(); err != nil {
		return true, err
	}
	pid := cmd.Process.Pid
	cmd.Process.Release()
	return true, writeFresh(pidFile, []byte(fmt.Sprintf("%d %s\n", pid, filepath.Base(p[0]))))
}
