// Tailors runs a command and, when it ends, tolls a bell: nine strokes, three
// if it was killed, then one for each full minute it ran.
package main

import (
	"errors"
	"fmt"
	"io/fs"
	"os"
	"os/exec"
	"os/signal"
	"strconv"
	"syscall"
	"time"
)

const notice = `tailors: tolls a bell when a command ends.

  tailors <command> [args...]    run it, then toll
  tailors                        stop a bell still ringing

Tellers
  9   the command ended on its own
  3   the command was ended for it (killed by a signal)
  1   more for each full minute it ran, at most 60

A command that did not succeed has its last stroke a semitone
flat. Under a minute, that is all. Nothing else is rung.

Input, output and exit status pass through untouched. A killed
command exits 128 plus the signal number.

TAILORS_PLAYER names the audio player, like PAGER.

normal is dead
`

func main() {
	args := os.Args[1:]
	switch {
	case len(args) == 0:
		stopped := stopBell()
		fmt.Print(notice)
		if stopped {
			fmt.Fprintln(os.Stderr, "tailors: the bell was stopped.")
		} else {
			fmt.Fprintln(os.Stderr, "tailors: no bell was ringing.")
		}
	case len(args) == 1 && args[0] == "--help":
		fmt.Print(notice)
	default:
		os.Exit(run(args))
	}
}

// run runs the command on the very same descriptors, tolls, and returns the
// status a shell would have seen without tailors.
func run(args []string) int {
	// Caught, never ignored: an ignored signal would stay ignored in the
	// command. A signal ignored by whoever started tailors is left as it was.
	sigs := make(chan os.Signal, 8)
	for _, s := range []os.Signal{syscall.SIGINT, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGHUP} {
		if !signal.Ignored(s) {
			signal.Notify(sigs, s)
		}
	}

	cmd := exec.Command(args[0], args[1:]...)
	if errors.Is(cmd.Err, exec.ErrDot) {
		cmd.Err = nil // a shell would run it from a relative PATH entry, so do the same
	}
	cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
	start := time.Now()
	if err := cmd.Start(); err != nil {
		fmt.Fprintf(os.Stderr, "tailors: nothing to toll. %q was not found.\n", args[0])
		if errors.Is(err, exec.ErrNotFound) || errors.Is(err, fs.ErrNotExist) {
			return 127
		}
		return 126
	}
	go func() {
		for s := range sigs {
			if s == syscall.SIGTERM || s == syscall.SIGHUP {
				cmd.Process.Signal(s)
			}
		}
	}()
	cmd.Wait() // a non-zero exit is not an error here; the status is read below
	elapsed := time.Since(start)

	ws := cmd.ProcessState.Sys().(syscall.WaitStatus)
	e, status := ending{code: ws.ExitStatus()}, ws.ExitStatus()
	if ws.Signaled() {
		e = ending{sig: ws.Signal()}
		status = 128 + int(ws.Signal())
	}
	toll(e, elapsed)

	if e.sig == syscall.SIGINT {
		// Die of SIGINT as the command did, so a shell loop stops on Ctrl-C.
		signal.Reset(syscall.SIGINT)
		syscall.Kill(os.Getpid(), syscall.SIGINT)
		time.Sleep(time.Second)
	}
	return status
}

// toll builds the peal, rings it, and leaves the record line on a terminal.
func toll(e ending, elapsed time.Duration) {
	prelude, minutes := strokeCount(e, elapsed)
	k := prelude + minutes
	pcm := wav(peal(prelude, minutes, e.failed()), record(e, elapsed, k, plain))
	tmp := base + "." + strconv.Itoa(os.Getpid()) + ".tmp"

	found, err := false, writeFresh(tmp, pcm)
	if err == nil {
		found, err = ring(tmp)
	}
	os.Remove(tmp) // gone after the rename; this only clears a failed write
	if !isTerminal(os.Stderr) {
		return
	}
	paint := plain
	if os.Getenv("NO_COLOR") == "" {
		paint = brick
	}
	fmt.Fprintln(os.Stderr, record(e, elapsed, k, paint)+".")
	switch {
	case err != nil:
		fmt.Fprintf(os.Stderr, "tailors: the bell could not be rung. %v.\n", err)
	case !found:
		fmt.Fprintf(os.Stderr, "tailors: no player found. The peal is at %s. It can be carried.\n", pealAt)
	}
}

func brick(s string) string { return "\x1b[38;2;236;94;82m" + s + "\x1b[39m" }

// isTerminal takes any character device for a terminal. /dev/null is one too,
// and a record line written there goes nowhere; a true isatty needs per-OS ioctls.
func isTerminal(f *os.File) bool {
	fi, err := f.Stat()
	return err == nil && fi.Mode()&os.ModeCharDevice != 0
}
