// Command nulltest compares two files by playing both through the same
// plucked string and keeping what is left when one is taken from the other.
package main

import (
	"bufio"
	"flag"
	"fmt"
	"io"
	"os"
	"os/exec"
	"os/signal"
	"time"
)

const (
	usage    = "usage: nulltest [-s seconds] [-o file] [-q] A [B]"
	maxBytes = 256 << 20
)

func main() {
	code, play := run(os.Args[1:], os.Stdout, os.Stderr)
	if play != "" && isTerminal(os.Stdout) {
		playWAV(play)
	}
	os.Exit(code)
}

// run does everything but play. It returns the exit status and the WAV to
// play, which is "" under -q or when no WAV was written.
func run(args []string, stdout, stderr io.Writer) (int, string) {
	fs := flag.NewFlagSet("nulltest", flag.ContinueOnError)
	fs.SetOutput(io.Discard)
	seconds := fs.Int("s", 10, "")
	out := fs.String("o", "null.wav", "")
	quiet := fs.Bool("q", false, "")
	if fs.Parse(args) != nil || fs.NArg() < 1 || fs.NArg() > 2 || *seconds < 2 || *seconds > 120 {
		fmt.Fprintln(stderr, usage)
		return 2, ""
	}
	outGiven := false
	fs.Visit(func(f *flag.Flag) { outGiven = outGiven || f.Name == "o" })

	paths := fs.Args()
	f := form{date: time.Now().Format("2006-01-02"), nameA: paths[0], single: len(paths) == 1}
	f.b.none = f.single
	var msg string
	if f.a.b, msg = read(paths[0], "A"); msg == "" && !f.single {
		f.nameB = paths[1]
		f.b.b, msg = read(paths[1], "B")
	}
	if msg != "" {
		fmt.Fprintln(stderr, msg)
		return 2, ""
	}

	res := measure(f.a, f.b, *seconds)
	if !*quiet || outGiven {
		if writeWAV(*out, res.pcm) == nil {
			f.wavPath = *out
		}
	}
	w := bufio.NewWriter(stdout)
	w.WriteString(sheet(f, res))
	w.Flush()

	code := 0
	if !f.single && !res.v.identical() {
		code = 1
	}
	if *quiet {
		return code, ""
	}
	return code, f.wavPath
}

// read refuses a file over 256 MiB before reading it, then reads it whole.
func read(path, side string) ([]byte, string) {
	if st, err := os.Stat(path); err == nil && st.Size() > maxBytes {
		return nil, "nulltest: " + side + " is larger than 256 MiB. Nothing was compared."
	}
	b, err := os.ReadFile(path)
	if err != nil {
		return nil, "nulltest: cannot read " + side + ": " + err.Error() + ". Nothing was compared."
	}
	if len(b) > maxBytes { // a pipe or device that stat could not size
		return nil, "nulltest: " + side + " is larger than 256 MiB. Nothing was compared."
	}
	return b, ""
}

func isTerminal(f *os.File) bool {
	st, err := f.Stat()
	return err == nil && st.Mode()&os.ModeCharDevice != 0
}

// playWAV runs the first player found and waits. SIGINT is caught and
// dropped while it plays, never ignored: an ignored SIGINT would pass to the
// player across exec, and Ctrl-C would no longer stop the sound.
func playWAV(path string) {
	players := [][]string{
		{"afplay", path},
		{"paplay", path},
		{"aplay", "-q", path},
		{"play", "-q", path},
		{"ffplay", "-nodisp", "-autoexit", "-loglevel", "quiet", path},
	}
	for _, p := range players {
		if _, err := exec.LookPath(p[0]); err != nil {
			continue
		}
		c := make(chan os.Signal, 1)
		signal.Notify(c, os.Interrupt)
		_ = exec.Command(p[0], p[1:]...).Run()
		signal.Stop(c)
		return
	}
}
