package main

import (
	"fmt"
	"io/fs"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"syscall"
	"time"
)

// realPath is the absolute path with symlinks resolved, or the absolute path
// when it cannot be resolved (it may be gone).
func realPath(p string) string {
	abs, err := filepath.Abs(p)
	if err != nil {
		return p
	}
	if r, err := filepath.EvalSymlinks(abs); err == nil {
		return r
	}
	return abs
}

// within is a separator aware prefix test: /a/b is within /a, not within /a/bc.
func within(p, root string) bool {
	return root == "/" || p == root || strings.HasPrefix(p, root+"/")
}

func uidOf(fi fs.FileInfo) int { return int(fi.Sys().(*syscall.Stat_t).Uid) }

func modeOf(fi fs.FileInfo) uint32 { return uint32(fi.Sys().(*syscall.Stat_t).Mode) & 0o7777 }

type plan struct {
	entries, locked, unchanged, notyours, symlinks, other int
	newest                                                time.Time
	newestPath                                            string
	rows                                                  []row
}

// planField lists the field without changing anything. Symlinks are never
// followed: a chmod on one would reach a file outside the field.
func planField(root string, uid int) (*plan, error) {
	p := &plan{}
	err := filepath.WalkDir(root, func(path string, _ fs.DirEntry, err error) error {
		rel, _ := filepath.Rel(root, path)
		if strings.Contains(rel, "\n") {
			return refuse("A name in this field contains a line break. Fallow cannot write it down.")
		}
		var fi fs.FileInfo
		if err == nil {
			fi, err = os.Lstat(path)
		}
		if err != nil {
			return refuse("%s cannot be read, so the field cannot be listed.", rel)
		}
		p.entries++
		if fi.ModTime().After(p.newest) {
			p.newest, p.newestPath = fi.ModTime(), rel
		}
		switch m := fi.Mode(); {
		case m&fs.ModeSymlink != 0:
			p.symlinks++
		case !m.IsRegular() && !m.IsDir():
			p.other++
		case uidOf(fi) != uid:
			p.notyours++
		case modeOf(fi)&0o222 == 0:
			p.unchanged++
		default:
			p.locked++
			p.rows = append(p.rows, row{fmt.Sprintf("%04o", modeOf(fi)), rel})
		}
		return nil
	})
	return p, err
}

func octal(r row) uint32 {
	m, _ := strconv.ParseUint(r.mode, 8, 32)
	return uint32(m)
}

// lock clears the write bits of every planned row. A failure is reported and
// the rest carry on; the row stays in the book, where it is harmless.
func lock(root string, rows []row) bool {
	ok := true
	for _, r := range rows {
		if err := syscall.Chmod(filepath.Join(root, r.path), octal(r)&^0o222); err != nil {
			fmt.Fprintf(os.Stderr, "%s could not be locked: %v.\n", r.path, err)
			ok = false
		}
	}
	return ok
}

// target is where a manifest row points inside root, or "" when the row must
// not be followed: a mode that is not four octal digits, an absolute path, a
// "..", or a parent directory that resolves outside the field. A book edited by
// hand must never make Fallow change a file outside the field.
func target(root string, r row) string {
	if len(r.mode) != 4 || strings.Trim(r.mode, "01234567") != "" || r.path == "" || filepath.IsAbs(r.path) {
		return ""
	}
	for _, part := range strings.Split(r.path, "/") {
		if part == ".." {
			return ""
		}
	}
	p := filepath.Join(root, r.path)
	if p == root {
		return p
	}
	parent, err := filepath.EvalSymlinks(filepath.Dir(p))
	if err != nil {
		return p // ponytail: the parent is gone, so Lstat of p fails and the row counts as gone
	}
	if !within(parent, root) {
		return ""
	}
	return filepath.Join(parent, filepath.Base(p))
}

// restore writes every recorded mode back exactly. Missing targets are counted
// as gone; symlinks and entries owned by someone else are skipped.
func restore(root string, e *entry) (restored, gone int, ok bool) {
	ok = true
	for _, r := range e.rows {
		p := target(root, r)
		if p == "" {
			fmt.Fprintf(os.Stderr, "Entry %d has a row Fallow will not follow: %s %s. It was ignored.\n", e.n, r.mode, r.path)
			continue
		}
		fi, err := os.Lstat(p)
		if err != nil {
			gone++
			continue
		}
		if fi.Mode()&fs.ModeSymlink != 0 || uidOf(fi) != os.Getuid() {
			continue
		}
		if err := syscall.Chmod(p, octal(r)); err != nil {
			fmt.Fprintf(os.Stderr, "%s could not be restored: %v.\n", r.path, err)
			ok = false
			continue
		}
		restored++
	}
	return restored, gone, ok
}

type evidence struct {
	found           bool
	changed         int
	newest          time.Time
	newestPath      string
	writable, total int
}

// gather reads only the file system: entries modified after the rest began,
// and locked rows that have a write bit again. It is the same for status and
// for plough.
func gather(root string, at time.Time, rows []row) evidence {
	var ev evidence
	if fi, err := os.Lstat(root); err != nil || !fi.IsDir() {
		return ev
	}
	ev.found = true
	filepath.WalkDir(root, func(path string, _ fs.DirEntry, err error) error {
		fi, lerr := os.Lstat(path)
		if err != nil || lerr != nil {
			return nil
		}
		if t := fi.ModTime(); t.After(at) {
			ev.changed++
			if t.After(ev.newest) {
				ev.newest = t
				ev.newestPath, _ = filepath.Rel(root, path)
			}
		}
		return nil
	})
	for _, r := range rows {
		p := target(root, r)
		if p == "" {
			continue
		}
		fi, err := os.Lstat(p)
		if err != nil || fi.Mode()&fs.ModeSymlink != 0 {
			continue
		}
		ev.total++
		if modeOf(fi)&0o222 != 0 {
			ev.writable++
		}
	}
	return ev
}

// lines words the evidence as what was found, never as a verdict.
func (ev evidence) lines() []string {
	if !ev.found {
		return []string{"Not found at this path."}
	}
	c := "Changed since rest: none found."
	if ev.changed > 0 {
		c = fmt.Sprintf("Changed since rest: %s. Newest: %s, %s.", plural(ev.changed, "entry", "entries"), fmtDay(ev.newest), ev.newestPath)
	}
	var w string
	switch {
	case ev.total == 0:
		w = "Write permission: no entries were locked."
	case ev.writable == 0 && ev.total == 1:
		w = "Write permission: held on the 1 locked entry."
	case ev.writable == 0:
		w = fmt.Sprintf("Write permission: held on all %d locked entries.", ev.total)
	default:
		w = fmt.Sprintf("Write permission: back on %d of %s.", ev.writable, plural(ev.total, "locked entry", "locked entries"))
	}
	return []string{c, w}
}

// carries counts the rows whose entry under dir has exactly the locked mode the
// row would have left. It is a trace of the locks, never a proof of descent.
func carries(dir string, rows []row) int {
	m := 0
	for _, r := range rows {
		p := target(dir, r)
		if p == "" {
			continue
		}
		if fi, err := os.Lstat(p); err == nil && fi.Mode()&fs.ModeSymlink == 0 && modeOf(fi) == octal(r)&^0o222 {
			m++
		}
	}
	return m
}
