// Command usually runs one command exactly as it would have run, keeps one line
// about it in a plain log, and says how long that command usually takes and
// whether this run was a usual one. Everything it says goes to stderr.
package main

import (
	"errors"
	"fmt"
	"io/fs"
	"os"
	"os/exec"
	"os/signal"
	"path/filepath"
	"strings"
	"syscall"
	"time"
)

const usage = `usage: usually <command> [args...]
Runs the command once, unchanged, and says how long it usually takes, from the runs you already made.
Everything it says goes to stderr. The command's input, output and exit code are left alone.
Log: %s
normal is dead
`

func main() {
	args := os.Args[1:]
	path := logPath()
	if len(args) == 0 {
		fmt.Fprintf(os.Stderr, usage, path)
		os.Exit(2)
	}
	if len(args) == 1 && args[0] == "-h" {
		fmt.Printf(usage, path)
		os.Exit(0)
	}

	cmd := exec.Command(args[0], args[1:]...)
	if errors.Is(cmd.Err, exec.ErrDot) {
		cmd.Err = nil // a shell would run it from a "." in PATH, so this does too
	}
	if cmd.Err == nil && strings.Contains(args[0], "/") {
		_, cmd.Err = exec.LookPath(args[0]) // exec.Command looks up bare names only; say nothing before a path that cannot start
	}
	if cmd.Err != nil {
		os.Exit(cannotStart(cmd.Err))
	}
	cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr

	cwd, _ := os.Getwd()
	k := newKey(cwd, args)
	h, readErr := readHistory(path, k)
	if readErr == nil {
		say(before(h, time.Now()))
	}

	// Notify and discard, never Ignore: SIG_IGN is inherited across exec and would
	// make the child immune to Ctrl-C. A signal that arrived already ignored (nohup,
	// a background job) is left ignored, so the child inherits it as it would have.
	sigs := make(chan os.Signal, 8)
	for _, s := range []os.Signal{syscall.SIGINT, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM} {
		if !signal.Ignored(s) {
			signal.Notify(sigs, s)
		}
	}
	start := time.Now()
	if err := cmd.Start(); err != nil {
		os.Exit(cannotStart(err))
	}
	go func() {
		for s := range sigs {
			if s == syscall.SIGTERM {
				_ = cmd.Process.Signal(s)
			}
		}
	}()
	_ = cmd.Wait()
	ms := (time.Since(start).Nanoseconds() + 500_000) / 1_000_000

	ws := cmd.ProcessState.Sys().(syscall.WaitStatus)
	code := ws.ExitStatus()
	if ws.Signaled() {
		code = 128 + int(ws.Signal())
	}
	werr := appendRun(path, logLine(time.Now(), ms, code, k))
	if lines := after(h, ms, code, werr != nil); len(lines) > 0 {
		say(append([]string{""}, lines...))
	}
	if ws.Signaled() {
		relay(ws.Signal())
	}
	os.Exit(code)
}

// relay dies by the child's signal, so the calling shell sees a death by signal
// and a loop stops on one Ctrl-C.
// ponytail: only HUP, INT, TERM and KILL die cleanly by a self-kill in Go. The
// runtime prints a crash trace for QUIT, SEGV, ABRT and the like, and ignores a
// sent PIPE or USR1, so those fall through to exit status 128 plus N.
func relay(sig syscall.Signal) {
	switch sig {
	case syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGKILL:
		signal.Reset(sig)
		_ = syscall.Kill(os.Getpid(), sig)
		time.Sleep(time.Second)
	}
}

func cannotStart(err error) int {
	fmt.Fprintln(os.Stderr, err)
	if errors.Is(err, exec.ErrNotFound) || errors.Is(err, fs.ErrNotExist) {
		return 127
	}
	return 126
}

func say(lines []string) {
	if len(lines) > 0 {
		os.Stderr.WriteString(strings.Join(lines, "\n") + "\n")
	}
}

func logPath() string {
	if p := os.Getenv("USUALLY_LOG"); p != "" {
		return p
	}
	home, _ := os.UserHomeDir()
	return filepath.Join(home, ".usually.log")
}
