package main

import (
	"context"
	"os"
	"os/exec"
	"strings"
	"time"
)

// Step is one way of ending the night: a name for the ledger and the program to run.
type Step struct {
	Name string
	Args []string
}

// Steps is the fallback chain for this platform and these flags.
func Steps(goos string, lock bool, then string) []Step {
	if then != "" {
		return []Step{{"then", []string{"sh", "-c", then}}}
	}
	var s []Step
	switch goos {
	case "darwin":
		s = []Step{{"suspend", []string{"pmset", "sleepnow"}}, {"lock", []string{"pmset", "displaysleepnow"}}}
	case "linux":
		s = []Step{{"suspend", []string{"systemctl", "suspend"}}, {"lock", []string{"loginctl", "lock-session"}}}
	default:
		return nil
	}
	if lock {
		s = s[1:]
	}
	return s
}

// Describe is the dry run's account of the chain. It says found or not found, never that a step will work.
func Describe(steps []Step) string {
	parts := []string{"none (this system has neither suspend nor lock)."}
	if len(steps) > 0 {
		parts = parts[:0]
	}
	for _, s := range steps {
		state := "found"
		if _, err := exec.LookPath(s.Args[0]); err != nil {
			state = "not found"
		}
		parts = append(parts, s.Name+" ("+s.Args[0]+" "+state+").")
	}
	return "Action: " + strings.Join(parts, " If that fails: ") + " If that fails: print and exit 3."
}

// Outcome is how the chain ended. At is the instant the deciding command was started.
type Outcome struct {
	Action string
	Failed []string
	At     time.Time
}

// RunSteps tries each step in order. The start instant is captured before each command runs,
// so a suspend that returns after waking still records when the machine was put to sleep.
func RunSteps(steps []Step, now func() time.Time) Outcome {
	o := Outcome{Action: "none", At: now()}
	for _, s := range steps {
		if _, err := exec.LookPath(s.Args[0]); err != nil {
			continue
		}
		o.At = now()
		ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
		cmd := exec.CommandContext(ctx, s.Args[0], s.Args[1:]...)
		cmd.Stdin = nil // reads from the null device, so it can never sit at a password prompt
		cmd.Stdout, cmd.Stderr = os.Stderr, os.Stderr
		err := cmd.Run()
		cancel()
		if err == nil {
			o.Action = s.Name
			return o
		}
		o.Failed = append(o.Failed, s.Name)
	}
	return o
}
