// Fallow rests a project directory for a number of seasons by clearing its
// write bits, and keeps a field book of what happened while it rested.
package main

import (
	"fmt"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"text/tabwriter"
	"time"
)

const usage = `Usage:
  fallow rest DIR --seasons N
  fallow plough DIR [--trespass]
  fallow status [DIR]

A season is three calendar months. A field may be ploughed on the first quarter day
(25 Mar, 24 Jun, 29 Sep, 25 Dec) on or after N seasons from the day it was rested.`

const caution = "A modification time can be moved by a backup, a sync or an indexer. This is evidence, not a finding."

// stop ends a command with an exit code and one sentence for stderr.
type stop struct {
	code int
	msg  string
}

func (s stop) Error() string { return s.msg }

var usageErr = stop{2, usage}

// refuse is every exit 1 refusal of rest and plough.
func refuse(format string, a ...any) error {
	return stop{1, fmt.Sprintf(format, a...) + " Nothing was changed."}
}

func main() { os.Exit(run(os.Args[1:])) }

func run(args []string) int {
	if len(args) == 0 {
		fmt.Fprintln(os.Stderr, usage)
		return 2
	}
	cmd := map[string]func([]string) error{"rest": rest, "plough": plough, "status": status}[args[0]]
	switch {
	case args[0] == "help" || args[0] == "-h" || args[0] == "--help":
		fmt.Println(usage)
		return 0
	case cmd == nil:
		fmt.Fprintln(os.Stderr, usage)
		return 2
	}
	err := cmd(args[1:])
	if err == nil {
		return 0
	}
	s, ok := err.(stop)
	if !ok {
		s = stop{1, err.Error()}
	}
	if s.msg != "" {
		fmt.Fprintln(os.Stderr, s.msg)
	}
	return s.code
}

// tilde writes the home directory as ~.
func tilde(p string) string {
	h, err := os.UserHomeDir()
	if h = filepath.Clean(h); err != nil || h == "/" {
		return p
	}
	for _, home := range []string{h, realPath(h)} {
		if p == home {
			return "~"
		}
		if strings.HasPrefix(p, home+"/") {
			return "~" + p[len(home):]
		}
	}
	return p
}

func iso(t time.Time) string { return t.Format(isoLayout) }

// resolveDir names a field by its real path and checks that it is a directory.
func resolveDir(arg string, fail func(string, ...any) error) (string, error) {
	p := realPath(arg)
	fi, err := os.Stat(p)
	switch {
	case os.IsNotExist(err):
		return p, fail("%s does not exist.", tilde(p))
	case err != nil:
		return p, fail("%s cannot be read, so the field cannot be listed.", tilde(p))
	case !fi.IsDir():
		return p, fail("%s is not a directory.", tilde(p))
	}
	return p, nil
}

// bookErr turns a failure to open or read the book into a refusal.
func bookErr(err error) error {
	if u, ok := err.(unreadable); ok {
		return refuse("%s", u.Error())
	}
	return refuse("The book cannot be opened: %v.", err)
}

func tooEarly(from time.Time, k int) string {
	return fmt.Sprintf("Not before %s. %s to go.", fmtDay(from), plural(k, "day", "days"))
}

func rest(args []string) error {
	day, err := today()
	if err != nil {
		return err
	}
	var dir, seasons string
	named := false
	for i := 0; i < len(args); i++ {
		switch a := args[i]; {
		case a == "--seasons":
			named = true
			if i+1 < len(args) {
				i++
				seasons = args[i]
			}
		case strings.HasPrefix(a, "--seasons="):
			named, seasons = true, strings.TrimPrefix(a, "--seasons=")
		case strings.HasPrefix(a, "-") || dir != "":
			return usageErr
		default:
			dir = a
		}
	}
	if dir == "" {
		return usageErr
	}
	if !named {
		return stop{2, "Say how long: fallow rest DIR --seasons N."}
	}
	n, err := strconv.Atoi(seasons)
	if err != nil || strings.Trim(seasons, "0123456789") != "" || n < 1 || n > 40 {
		return stop{2, "Seasons are counted in whole numbers from 1 to 40."}
	}
	if os.Geteuid() == 0 {
		fmt.Fprintln(os.Stderr, "You are root. Permissions do not bind root; only the book will hold.")
	}
	bp, err := bookPath()
	if err != nil {
		return err
	}
	field, err := resolveDir(dir, refuse)
	if err != nil {
		return err
	}
	f, es, err := openBook(bp, false)
	if err != nil && !os.IsNotExist(err) {
		return bookErr(err)
	}
	if f != nil {
		defer f.Close()
	}
	if err := mayRest(field, bp, es); err != nil {
		return err
	}

	at := time.Now()
	p, err := planField(field, os.Getuid())
	if err != nil {
		return err
	}
	if f == nil {
		// The first rest creates the book; a rest that ran alongside may have made it first.
		if f, es, err = openBook(bp, true); err != nil {
			return bookErr(err)
		}
		defer f.Close()
		if err := mayRest(field, bp, es); err != nil {
			return err
		}
	}
	from := ploughDay(day, n)
	body := lines("did", "rested", "date", iso(day), "at", at.Format(atLayout), "field", field,
		"seasons", strconv.Itoa(n), "from", iso(from),
		"newest", p.newest.Format(atLayout)+" "+p.newestPath,
		"entries", strconv.Itoa(p.entries), "locked", strconv.Itoa(p.locked),
		"unchanged", strconv.Itoa(p.unchanged), "notyours", strconv.Itoa(p.notyours),
		"symlinks", strconv.Itoa(p.symlinks), "other", strconv.Itoa(p.other),
		"note", "Resting. Nothing was deleted or moved.")
	for _, r := range p.rows {
		body = append(body, "  "+r.mode+" "+r.path+"\n"...)
	}
	num, sealed, err := appendEntry(f, es, body)
	if err != nil {
		return refuse("The book could not be written: %v.", err)
	}
	ok := lock(field, p.rows)

	var left []string
	for _, c := range []struct {
		n    int
		what string
	}{{p.unchanged, "already read-only"}, {p.notyours, "not yours"}, {p.symlinks, "symlinks"}, {p.other, "neither file nor directory"}} {
		if c.n == 1 && c.what == "symlinks" {
			c.what = "symlink"
		}
		if c.n > 0 {
			left = append(left, fmt.Sprintf("%d %s", c.n, c.what))
		}
	}
	fmt.Printf("Resting %s\n", tilde(field))
	fmt.Printf("  %s, %d locked.\n", plural(p.entries, "entry", "entries"), p.locked)
	if len(left) > 0 {
		fmt.Printf("  Left as found: %s.\n", strings.Join(left, ", "))
	}
	fmt.Printf("  Last touched %s (%s).\n", fmtDay(p.newest), p.newestPath)
	fmt.Println("  Nothing was deleted or moved. Reading is unchanged.")
	fmt.Printf("  Rested %s for %s. Ploughing from %s.\n", fmtDay(day), plural(n, "season", "seasons"), fmtDay(from))
	fmt.Printf("  Entered as no. %d. Seal %s.\n", num, sealed)
	if !ok {
		return stop{1, ""}
	}
	return nil
}

// mayRest refuses a field that is resting, holds the book, or overlaps a resting field.
func mayRest(field, bp string, es []*entry) error {
	rests, _, open := ledger(es)
	if r := open[field]; r != nil {
		return refuse("%s is already resting. Ploughing from %s.", tilde(field), fmtDay(r.from))
	}
	if within(filepath.Join(realPath(filepath.Dir(bp)), filepath.Base(bp)), field) {
		return refuse("%s holds the field book. Fallow will not rest it.", tilde(field))
	}
	for _, r := range rests {
		switch {
		case open[r.field] != r:
		case within(field, r.field):
			return refuse("%s lies inside the resting field %s.", tilde(field), tilde(r.field))
		case within(r.field, field):
			return refuse("%s holds the resting field %s.", tilde(field), tilde(r.field))
		}
	}
	if strings.Contains(field, "\n") {
		return refuse("A name in this field contains a line break. Fallow cannot write it down.")
	}
	return nil
}

func plough(args []string) error {
	day, err := today()
	if err != nil {
		return err
	}
	var dir string
	trespass := false
	for _, a := range args {
		switch {
		case a == "--trespass":
			trespass = true
		case strings.HasPrefix(a, "-") || dir != "":
			return usageErr
		default:
			dir = a
		}
	}
	if dir == "" {
		return usageErr
	}
	bp, err := bookPath()
	if err != nil {
		return err
	}
	field := realPath(dir)
	f, es, err := openBook(bp, false)
	if os.IsNotExist(err) {
		return refuse("%s is not resting.", tilde(field))
	}
	if err != nil {
		return bookErr(err)
	}
	defer f.Close()
	_, _, open := ledger(es)
	r := open[field]
	if r == nil {
		return refuse("%s is not resting.", tilde(field))
	}
	early, k := day.Before(r.from), daysBetween(day, r.from)
	if early && !trespass {
		return refuse("%s", tooEarly(r.from, k))
	}

	ev := gather(field, r.at, r.rows)
	restored, gone, ok := restore(field, r)
	did, note := "ploughed", "Ploughed on the quarter day."
	if early {
		did = "trespassed"
		note = fmt.Sprintf("Ploughed early on %s, %s before %s. The field was posted, not fenced.", iso(day), plural(k, "day", "days"), iso(r.from))
	} else if k < 0 {
		note = fmt.Sprintf("Ploughed %s after the quarter day.", plural(-k, "day", "days"))
	}
	changed := "0"
	if ev.changed > 0 {
		changed = fmt.Sprintf("%d %s %s", ev.changed, ev.newest.Format(atLayout), ev.newestPath)
	}
	kv := []string{"did", did, "date", iso(day), "at", time.Now().Format(atLayout), "field", field,
		"of", strconv.Itoa(r.n), "restored", strconv.Itoa(restored), "gone", strconv.Itoa(gone),
		"changed", changed, "writable", fmt.Sprintf("%d %d", ev.writable, ev.total)}
	if !ev.found {
		kv = append(kv, "found", "no")
	}
	num, sealed, err := appendEntry(f, es, lines(append(kv, "note", note)...))
	if err != nil {
		return stop{1, fmt.Sprintf("The modes were restored, but the book could not be written: %v.", err)}
	}

	head := "Ploughed"
	if early {
		head = "Ploughed early"
	}
	fmt.Printf("%s %s\n", head, tilde(field))
	if restored == 1 {
		fmt.Println("  1 entry restored to the mode it had.")
	} else {
		fmt.Printf("  %d entries restored to the modes they had.\n", restored)
	}
	if gone > 0 {
		fmt.Printf("  %d no longer there.\n", gone)
	}
	fmt.Printf("  Rested %s for %s. Ploughed %s.\n", fmtDay(r.date), plural(r.seasons, "season", "seasons"), fmtDay(day))
	for _, l := range ev.lines() {
		fmt.Println("  " + l)
	}
	if early {
		fmt.Printf("  Ploughed early, %s before %s. The field was posted, not fenced.\n", plural(k, "day", "days"), fmtDay(r.from))
	}
	fmt.Printf("  Entered as no. %d. Seal %s.\n", num, sealed)
	if !ok {
		return stop{1, ""}
	}
	return nil
}

func status(args []string) error {
	day, err := today()
	if err != nil {
		return err
	}
	if len(args) > 1 || len(args) == 1 && strings.HasPrefix(args[0], "-") {
		return usageErr
	}
	bp, err := bookPath()
	if err != nil {
		return err
	}
	es, err := readBook(bp)
	if err != nil {
		return stop{1, err.Error()}
	}
	brk := verify(es)
	var end error
	if brk != "" {
		end = stop{1, ""}
	}
	rests, closedBy, open := ledger(es)
	if len(args) == 1 {
		return statusDir(args[0], day, brk, end, rests, open)
	}
	if len(es) == 0 {
		fmt.Println("No field book yet. Nothing is resting.")
		return nil
	}

	chain := "each follows the one before."
	if brk != "" {
		chain = brk
	}
	fmt.Println("FIELD BOOK")
	fmt.Printf("%s  %s, %s  Seal %s\n\n", tilde(bp), plural(len(es), "entry", "entries"), chain, seal(es[len(es)-1]))
	tw := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
	fmt.Fprintln(tw, "FIELD\tRESTED\tSEASONS\tPLOUGH FROM\tSTATE\tCROP")
	for i, r := range rests {
		state := "resting"
		if c := closedBy[r]; c != nil {
			state = "ploughed " + fmtDay(c.date)
			if c.did == "trespassed" {
				state = "ploughed early " + fmtDay(c.date)
			}
		}
		fmt.Fprintf(tw, "%s\t%s\t%d\t%s\t%s\t%s\n", tilde(r.field), fmtDay(r.date), r.seasons, fmtDay(r.from), state, cropFor(i+1))
	}
	tw.Flush()

	showed := false
	for _, r := range rests {
		var block []string
		if c := closedBy[r]; open[r.field] == r {
			var s bool
			block, s = restingBlock(r, day)
			showed = showed || s
		} else if c != nil && (c.did == "trespassed" || c.ev.changed > 0 || c.ev.writable > 0) {
			block = closedBlock(r, c)
		}
		if block != nil {
			fmt.Printf("\n%s\n", strings.Join(block, "\n"))
		}
	}
	if showed {
		fmt.Printf("\n%s\n", caution)
	}
	return end
}

// restingBlock is the block of a resting field, and whether its evidence showed
// a change or a write bit that came back.
func restingBlock(r *entry, day time.Time) ([]string, bool) {
	allowed := fmt.Sprintf("Ploughing allowed from %s (%s).", fmtDay(r.from), plural(daysBetween(day, r.from), "day", "days"))
	if !day.Before(r.from) {
		allowed = fmt.Sprintf("Ploughing allowed since %s.", fmtDay(r.from))
	}
	ev := gather(r.field, r.at, r.rows)
	out := []string{tilde(r.field), fmt.Sprintf("  Rested %s for %s. %s", fmtDay(r.date), plural(r.seasons, "season", "seasons"), allowed)}
	for _, l := range ev.lines() {
		out = append(out, "  "+l)
	}
	return out, ev.found && (ev.changed > 0 || ev.writable > 0)
}

// closedBlock shows the evidence that was frozen into the book at ploughing.
func closedBlock(r, c *entry) []string {
	rested := fmt.Sprintf("  Rested %s for %s.", fmtDay(r.date), plural(r.seasons, "season", "seasons"))
	out := []string{tilde(r.field)}
	if c.did == "trespassed" {
		out = append(out, rested, fmt.Sprintf("  Ploughed early %s, %s before %s. The field was posted, not fenced.",
			fmtDay(c.date), plural(daysBetween(c.date, r.from), "day", "days"), fmtDay(r.from)))
	} else {
		out = append(out, fmt.Sprintf("%s Ploughed %s.", rested, fmtDay(c.date)))
	}
	out = append(out, "  Found at ploughing:")
	for _, l := range c.ev.lines() {
		out = append(out, "    "+l)
	}
	return out
}

// statusDir reads one directory and never writes: a resting field shows its
// block, and a directory the book does not know is matched by the locked modes
// it carries, which cp -a, tar and rsync -a keep.
func statusDir(arg string, day time.Time, brk string, end error, rests []*entry, open map[string]*entry) error {
	dir, err := resolveDir(arg, func(f string, a ...any) error { return stop{1, fmt.Sprintf(f, a...)} })
	if err != nil {
		return err
	}
	if brk != "" {
		fmt.Println(brk)
	}
	p := tilde(dir)
	if r := open[dir]; r != nil {
		block, showed := restingBlock(r, day)
		fmt.Println(strings.Join(block, "\n"))
		if showed {
			fmt.Printf("\n%s\n", caution)
		}
		return end
	}
	for _, r := range rests {
		if r.field == dir {
			fmt.Printf("%s is not resting.\n", p)
			return end
		}
	}
	found := false
	for _, r := range rests {
		if open[r.field] != r || len(r.rows) == 0 {
			continue
		}
		if m := carries(dir, r.rows); m > 0 {
			fmt.Printf("%s is not in the book. It carries the locks of entry %d (%s): %d of %s.\n",
				p, r.n, tilde(r.field), m, plural(len(r.rows), "locked entry", "locked entries"))
			found = true
		}
	}
	if !found {
		fmt.Printf("%s is not in the book.\n", p)
	}
	return end
}
