// The mbf program is a frontend for [hakurei.app/internal/rosa].
//
// This program is not covered by the compatibility promise. The command line
// interface, available packages and their behaviour, and even the on-disk
// format, may change at any time.
//
// # Name
//
// The name mbf stands for maiden's best friend, as a tribute to the DOOM source
// port of [the same name]. This name is a placeholder and is subject to change.
//
// [the same name]: https://www.doomwiki.org/wiki/MBF
package main

import (
	"context"
	"crypto/ed25519"
	"crypto/sha512"
	"errors"
	"fmt"
	"io"
	"log"
	"net"
	"net/http"
	"os"
	"os/signal"
	"path/filepath"
	"runtime"
	"strconv"
	"strings"
	"sync"
	"sync/atomic"
	"syscall"
	"time"
	"unique"
	"unsafe"

	"hakurei.app/check"
	"hakurei.app/command"
	"hakurei.app/container"
	"hakurei.app/ext"
	"hakurei.app/fhs"
	"hakurei.app/internal/pkg"
	"hakurei.app/internal/rosa"
	"hakurei.app/message"

	"hakurei.app/cmd/mbf/internal/pkgserver"
	"hakurei.app/cmd/mbf/internal/pkgserver/ui"
)

// writeFileExcl is like [os.WriteFile], but sets [os.O_EXCL] instead.
func writeFileExcl(name string, data []byte, perm os.FileMode) error {
	f, err := os.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_EXCL, perm)
	if err != nil {
		return err
	}
	_, err = f.Write(data)
	if err1 := f.Close(); err1 != nil && err == nil {
		err = err1
	}
	return err
}

func main() {
	container.TryArgv0(nil)

	log.SetFlags(0)
	log.SetPrefix("mbf: ")
	msg := message.New(log.Default())

	if os.Geteuid() == 0 {
		log.Fatal("this program must not run as root")
	}

	defer func() {
		r := recover()
		if r == nil {
			return
		}

		switch r.(type) {
		case rosa.LoadError, pkg.IRStringError:
			log.Fatal(r)
		default:
			panic(r)
		}
	}()

	ctx, stop := signal.NotifyContext(context.Background(),
		syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)
	defer stop()

	var cm cache
	defer func() { cm.Close() }()

	var (
		flagQuiet bool
		flagQEMU  bool
		flagArch  string
		flagCheck bool
		flagLTO   bool
		flagPT    bool
		flagDry   bool
		flagPath  string

		flagSourcePath    string
		flagCrossOverride int

		addr net.UnixAddr
	)
	c := command.New(os.Stderr, log.Printf, "mbf", func([]string) error {
		if !rosa.Native().HasStageEarly() {
			return pkg.UnsupportedArchError(runtime.GOARCH)
		}

		if flagPT {
			log.Println("parsed in", rosa.ParseTime())
		}

		msg.SwapVerbose(!flagQuiet)
		cm.ctx, cm.msg = ctx, msg
		cm.base = os.ExpandEnv(cm.base)
		if cm.base == "" {
			cm.base = "cache"
		}
		cm.mirror = os.ExpandEnv(cm.mirror)
		azaleaPath := os.ExpandEnv(flagPath)

		addr.Net = "unix"
		addr.Name = os.ExpandEnv(addr.Name)
		if addr.Name == "" {
			addr.Name = filepath.Join(cm.base, "daemon")
		}

		var flags int
		if !flagCheck {
			flags |= rosa.OptSkipCheck
		}
		if !flagLTO {
			flags |= rosa.OptLLVMNoLTO
		}
		rosa.Native().DropCaches("", flags)
		cross := flagArch != "" && flagArch != runtime.GOARCH
		if flagQEMU || cross {
			_, cm.qemu = rosa.Native().Std().MustLoad(rosa.H("qemu"))
		}

		if cross {
			if flagCrossOverride != -1 {
				flags = flagCrossOverride
			}

			rosa.Native().DropCaches(flagArch, flags)
			if !rosa.Native().HasStageEarly() {
				return pkg.UnsupportedArchError(flagArch)
			}
		}

		if flagSourcePath != "" {
			if err := rosa.Native().SetSource(os.DirFS(flagSourcePath)); err != nil {
				return err
			}
		}

		if azaleaPath != "" {
			var root *os.Root
			if a, err := check.NewAbs(azaleaPath); err != nil {
				return err
			} else if root, err = os.OpenRoot(a.String()); err != nil {
				return err
			} else if err = rosa.Native().RegisterFS(root.FS()); err != nil {
				return err
			}
		}

		return nil
	}).Flag(
		&flagQuiet,
		"q", command.BoolFlag(false),
		"Do not print cure messages",
	).Flag(
		&flagQEMU,
		"register", command.BoolFlag(false),
		"Enable additional target architectures",
	).Flag(
		&flagArch,
		"arch", command.StringFlag(runtime.GOARCH),
		"Target architecture",
	).Flag(
		&flagLTO,
		"lto", command.BoolFlag(false),
		"Enable LTO in stage2 and stage3 LLVM toolchains",
	).Flag(
		&flagCheck,
		"check", command.BoolFlag(true),
		"Run test suites",
	).Flag(
		&flagCrossOverride,
		"cross-flags", command.IntFlag(-1),
		"Override non-native target preset flags",
	).Flag(
		&cm.verboseInit,
		"v", command.BoolFlag(false),
		"Do not suppress verbose output from init",
	).Flag(
		&cm.attr.Cures,
		"cures", command.IntFlag(0),
		"Maximum number of dependencies to cure at any given time",
	).Flag(
		&cm.attr.Jobs,
		"jobs", command.IntFlag(0),
		"Preferred number of jobs to run, when applicable",
	).Flag(
		&cm.attr.Load,
		"load-average", command.IntFlag(0),
		"Preferred load average number, when applicable",
	).Flag(
		&cm.base,
		"d", command.StringFlag("$MBF_CACHE_DIR"),
		"Directory to store cured artifacts",
	).Flag(
		&cm.mirror,
		"r", command.StringFlag("$MBF_REMOTE"),
		"URL of mirror service",
	).Flag(
		&cm.deep,
		"deep", command.BoolFlag(false),
		"Cure all inputs even when the required artifact is available "+
			"via the mirror service",
	).Flag(
		&cm.idle,
		"sched-idle", command.BoolFlag(false),
		"Set SCHED_IDLE scheduling policy",
	).Flag(
		&cm.hostAbstract,
		"host-abstract", command.BoolFlag(
			os.Getenv("MBF_HOST_ABSTRACT") != "",
		),
		"Do not restrict networked cure containers from connecting to host "+
			"abstract UNIX sockets",
	).Flag(
		&addr.Name,
		"socket", command.StringFlag("$MBF_DAEMON_SOCKET"),
		"Pathname of socket to bind to",
	).Flag(
		&flagPT,
		"parse-time", command.BoolFlag(false),
		"Print duration of the initial azalea parse",
	).Flag(
		&flagDry,
		"dry", command.BoolFlag(false),
		"Do not destroy cache entries",
	).Flag(
		&flagSourcePath,
		"source", command.StringFlag(""),
		"Override hakurei source tree",
	).Flag(
		&flagPath,
		"p", command.StringFlag("$AZALEA_PATH"),
		"Load additional azalea files",
	)

	c.NewCommand(
		"checksum", "Compute checksum of data read from standard input",
		func([]string) error {
			done := make(chan struct{})
			defer close(done)
			go func() {
				select {
				case <-ctx.Done():
					os.Exit(1)
				case <-done:
					return
				}
			}()

			h := sha512.New384()
			if _, err := io.Copy(h, os.Stdin); err != nil {
				return err
			}
			log.Println(pkg.Encode(pkg.Checksum(h.Sum(nil))))
			return nil
		},
	)

	{
		var flagShifts int
		c.NewCommand(
			"scrub", "Examine the on-disk cache for errors",
			func(args []string) error {
				if len(args) > 0 {
					return errors.New("scrub expects no arguments")
				}
				if flagShifts < 0 || flagShifts > 31 {
					flagShifts = 12
				}
				return cm.Do(func(cache *pkg.Cache) error {
					return cache.Scrub(runtime.NumCPU() << flagShifts)
				})
			},
		).Flag(
			&flagShifts,
			"shift", command.IntFlag(12),
			"Scrub parallelism size exponent, to the power of 2",
		)
	}

	{
		var (
			flagBind   string
			flagStatus bool
			flagReport string
		)
		c.NewCommand(
			"info",
			"Display out-of-band metadata of an artifact",
			func(args []string) (err error) {
				const shutdownTimeout = 15 * time.Second

				var r *rosa.Report
				if flagReport != "" {
					if r, err = rosa.OpenReport(flagReport); err != nil {
						return err
					}
					defer func() {
						if closeErr := r.Close(); err == nil {
							err = closeErr
						}
					}()
					defer r.HandleAccess(&err)()
				}

				if flagBind == "" {
					return commandInfo(&cm, args, os.Stdout, flagStatus, r)
				}

				var mux http.ServeMux
				ui.Register(&mux)
				if err = pkgserver.Register(ctx, &mux, r); err != nil {
					return
				}

				server := http.Server{Addr: flagBind, Handler: &mux}
				go func() {
					<-ctx.Done()
					cc, cancel := context.WithTimeout(context.Background(), shutdownTimeout)
					defer cancel()
					if _err := server.Shutdown(cc); _err != nil {
						log.Fatal(_err)
					}
				}()

				msg.Verbosef("listening on %q", flagBind)
				err = server.ListenAndServe()
				if errors.Is(err, http.ErrServerClosed) {
					err = nil
				}
				return
			},
		).Flag(
			&flagBind,
			"bind", command.StringFlag(""),
			"TCP address for the server to listen on",
		).Flag(
			&flagStatus,
			"status", command.BoolFlag(false),
			"Display cure status if available",
		).Flag(
			&flagReport,
			"report", command.StringFlag(""),
			"Load cure status from this report file instead of cache",
		)
	}

	c.NewCommand(
		"report",
		"Generate an artifact cure report for the current cache",
		func(args []string) (err error) {
			var w *os.File
			switch len(args) {
			case 0:
				w = os.Stdout

			case 1:
				if w, err = os.OpenFile(
					args[0],
					os.O_CREATE|os.O_EXCL|syscall.O_WRONLY,
					0400,
				); err != nil {
					return
				}
				defer func() {
					closeErr := w.Close()
					if err == nil {
						err = closeErr
					}
				}()

			default:
				return errors.New("report requires 1 argument")
			}

			if ext.Isatty(int(w.Fd())) {
				return errors.New("output appears to be a terminal")
			}
			return cm.Do(func(cache *pkg.Cache) error {
				return rosa.WriteReport(msg, w, cache)
			})
		},
	)

	{
		var (
			flagJobs    int
			flagNoBlock bool
		)
		c.NewCommand("updates", command.UsageInternal, func([]string) error {
			var (
				errsMu sync.Mutex
				errs   []error

				n atomic.Uint64
			)

			w := make(chan rosa.ArtifactH)
			var wg sync.WaitGroup
			for range max(flagJobs, 1) {
				wg.Go(func() {
					for p := range w {
						meta, _ := rosa.Native().Std().MustLoad(p)
						if meta.ID == 0 {
							continue
						}

						if !flagNoBlock && meta.Blocked != "" {
							msg.Verbosef("%s is blocked: %s", meta.Name, meta.Blocked)
							continue
						}

						v, err := meta.GetVersions(ctx)
						if err != nil {
							errsMu.Lock()
							errs = append(errs, err)
							errsMu.Unlock()
							continue
						}

						if latest := meta.GetLatest(v); meta.Version != latest {
							n.Add(1)
							log.Printf("%s %s < %s", meta.Name, meta.Version, latest)
							continue
						}

						msg.Verbosef("%s is up to date", meta.Name)
					}
				})
			}

		done:
			for _, p := range rosa.Native().CollectAll() {
				select {
				case w <- p:
					break
				case <-ctx.Done():
					break done
				}
			}
			close(w)
			wg.Wait()

			if v := n.Load(); v > 0 {
				errs = append(errs, errors.New(strconv.Itoa(int(v))+
					" package(s) are out of date"))
			}
			return errors.Join(errs...)
		}).Flag(
			&flagJobs,
			"j", command.IntFlag(32),
			"Maximum number of simultaneous connections",
		).Flag(
			&flagNoBlock,
			"ignore-block", command.BoolFlag(false),
			"Inhibit update blocking",
		)
	}

	c.NewCommand("blocked", command.UsageInternal, func([]string) error {
		for _, p := range rosa.Native().CollectAll() {
			meta, _ := rosa.Native().Std().Load(p)
			if meta.Blocked != "" {
				fmt.Printf("%s: %s\n", meta.Name, meta.Blocked)
			}
		}
		return nil
	})

	c.NewCommand(
		"daemon",
		"Service artifact IR with Rosa OS extensions",
		func(args []string) error {
			ul, err := net.ListenUnix("unix", &addr)
			if err != nil {
				return err
			}
			log.Printf("listening on pathname socket at %s", addr.Name)
			return serve(ctx, log.Default(), &cm, ul)
		},
	)

	c.NewCommand(
		"keygen",
		"Create keypair for local cache",
		func([]string) error {
			pub, priv, err := ed25519.GenerateKey(nil)
			if err != nil {
				return err
			}

			return errors.Join(writeFileExcl(filepath.Join(
				cm.base,
				"ed25519.pub",
			), pub, 0444), writeFileExcl(filepath.Join(
				cm.base,
				"ed25519",
			), priv, 0400))
		},
	)

	c.NewCommand(
		"serve",
		"Export local cache as mirror",
		func(args []string) error {
			const shutdownTimeout = 15 * time.Second

			if len(args) != 1 {
				return errors.New("serve requires 1 argument")
			}

			var key ed25519.PrivateKey
			if p, err := os.ReadFile(filepath.Join(cm.base, "ed25519")); err != nil {
				return err
			} else if len(p) != ed25519.PrivateKeySize {
				return errors.New("invalid private key")
			} else {
				key = p
			}

			var h http.Handler
			if base, err := os.OpenRoot(cm.base); err != nil {
				return err
			} else {
				var mux http.ServeMux
				rosa.NewMirror(msg, base.FS(), key).Register(&mux)
				h = &mux
			}

			server := http.Server{Addr: args[0], Handler: h}
			go func() {
				<-ctx.Done()
				cc, cancel := context.WithTimeout(context.Background(), shutdownTimeout)
				defer cancel()
				if err := server.Shutdown(cc); err != nil {
					log.Fatal(err)
				}
			}()

			msg.Verbosef("listening on %q", args[0])
			err := server.ListenAndServe()
			if errors.Is(err, http.ErrServerClosed) {
				err = nil
			}
			return err
		},
	)

	c.NewCommand(
		"snapshot",
		"Populate an empty directory with a static mirror snapshot",
		func(args []string) error {
			if len(args) != 1 {
				return errors.New("snapshot requires 1 argument")
			}

			var key ed25519.PrivateKey
			if p, err := os.ReadFile(filepath.Join(cm.base, "ed25519")); err != nil {
				return err
			} else if len(p) != ed25519.PrivateKeySize {
				return errors.New("invalid private key")
			} else {
				key = p
			}

			var m rosa.Mirror
			if base, err := os.OpenRoot(cm.base); err != nil {
				return err
			} else {
				m = rosa.NewMirror(msg, base.FS(), key)
			}

		retry:
			root, err := os.OpenRoot(args[0])
			if err != nil {
				if os.IsNotExist(err) {
					if err = os.MkdirAll(args[0], 0755); err != nil {
						return err
					}
					goto retry
				}
				return err
			}

			go func() { <-ctx.Done(); _ = root.Close() }()
			return m.Populate(root)
		},
	)

	{
		var (
			flagGentoo   string
			flagChecksum string
		)
		c.NewCommand(
			"stage3",
			"Check for toolchain 3-stage non-determinism",
			func(args []string) (err error) {
				s := rosa.Std
				if flagGentoo != "" {
					s -= 3 // magic number to discourage misuse

					var checksum pkg.Checksum
					if len(flagChecksum) != 0 {
						if err = pkg.Decode(&checksum, flagChecksum); err != nil {
							return
						}
					}
					rosa.Native().SetGentooStage3(flagGentoo, checksum)
				}

				var (
					pathname *check.Absolute
					checksum [2]unique.Handle[pkg.Checksum]
				)

				_llvm := rosa.H("llvm")
				if err = cm.Do(func(cache *pkg.Cache) (err error) {
					_, llvm := rosa.Native().New(s - 2).Load(_llvm)
					pathname, _, err = cache.Cure(llvm)
					return
				}); err != nil {
					return
				}
				log.Println("stage1:", pathname)

				if err = cm.Do(func(cache *pkg.Cache) (err error) {
					_, llvm := rosa.Native().New(s - 1).Load(_llvm)
					pathname, checksum[0], err = cache.Cure(llvm)
					return
				}); err != nil {
					return
				}
				log.Println("stage2:", pathname)
				if err = cm.Do(func(cache *pkg.Cache) (err error) {
					_, llvm := rosa.Native().New(s).Load(_llvm)
					pathname, checksum[1], err = cache.Cure(llvm)
					return
				}); err != nil {
					return
				}
				log.Println("stage3:", pathname)

				if checksum[0] != checksum[1] {
					err = &pkg.ChecksumMismatchError{
						Got:  checksum[0].Value(),
						Want: checksum[1].Value(),
					}
				} else {
					log.Println(
						"stage2 is identical to stage3",
						"("+pkg.Encode(checksum[0].Value())+")",
					)
				}
				return
			},
		).Flag(
			&flagGentoo,
			"gentoo", command.StringFlag(""),
			"Bootstrap from a Gentoo stage3 tarball",
		).Flag(
			&flagChecksum,
			"checksum", command.StringFlag(""),
			"Checksum of Gentoo stage3 tarball",
		)
	}

	{
		var (
			flagDump    string
			flagEnter   bool
			flagExport  string
			flagRemote  bool
			flagNoReply bool
			flagFaults  bool
			flagPop     bool
			flagRebuild bool

			flagBoot bool
			flagStd  bool
		)
		c.NewCommand(
			"cure",
			"Cure the named artifact and show its path",
			func(args []string) error {
				if len(args) != 1 {
					return errors.New("cure requires 1 argument")
				}

				t := rosa.Std
				if flagBoot {
					t -= 2
				} else if flagStd {
					t -= 1
				}

				_, a := rosa.Native().New(t).Load(rosa.ArtifactH(unique.Make(args[0])))
				if a == nil {
					return fmt.Errorf("unknown artifact %q", args[0])
				}

				switch {
				default:
					var pathname *check.Absolute
					err := cm.Do(func(cache *pkg.Cache) (err error) {
						if flagRebuild {
							pathname, _, err = cache.CureNew(a)
						} else {
							pathname, _, err = cache.Cure(a)
						}
						return
					})
					if err != nil {
						return err
					}
					log.Println(pathname)

					if flagExport != "" {
						msg.Verbosef("exporting %s to %s...", args[0], flagExport)

						var f *os.File
						if f, err = os.OpenFile(
							flagExport,
							os.O_WRONLY|os.O_CREATE|os.O_EXCL,
							0400,
						); err != nil {
							return err
						} else if err = pkg.Write(
							os.DirFS(pathname.String()),
							".",
							f,
						); err != nil {
							_ = f.Close()
							return err
						} else if err = f.Close(); err != nil {
							return err
						}
					}

					return nil

				case flagDump != "":
					f, err := os.OpenFile(
						flagDump,
						os.O_WRONLY|os.O_CREATE|os.O_EXCL,
						0644,
					)
					if err != nil {
						return err
					}

					if err = pkg.NewIR().EncodeAll(f, a); err != nil {
						_ = f.Close()
						return err
					}

					return f.Close()

				case flagEnter:
					return cm.Do(func(cache *pkg.Cache) error {
						return cache.EnterExec(
							ctx,
							a,
							"", true, os.Stdin, os.Stdout, os.Stderr,
							rosa.AbsSystem.Append("bin", "mksh"),
							"sh",
						)
					})

				case flagRemote:
					var flags uint64
					if flagNoReply {
						flags |= remoteNoReply
					}
					pathname, err := cureRemote(ctx, &addr, a, flags)
					if !flagNoReply && err == nil {
						log.Println(pathname)
					}

					if errors.Is(err, context.Canceled) {
						cc, cancel := context.WithDeadline(context.Background(), daemonDeadline())
						defer cancel()

						if _err := cancelRemote(cc, &addr, a, false); _err != nil {
							log.Println(err)
						}
					}

					return err

				case flagFaults:
					var faults []pkg.Fault
					if err := cm.Do(func(cache *pkg.Cache) (err error) {
						faults, err = cache.ReadFaults(a)
						return
					}); err != nil {
						return err
					}

					for _, fault := range faults {
						log.Printf("%s: %s ago", fault.String(), time.Since(fault.Time()))
					}
					return nil

				case flagPop:
					var faults []pkg.Fault
					if err := cm.Do(func(cache *pkg.Cache) (err error) {
						faults, err = cache.ReadFaults(a)
						return
					}); err != nil {
						return err
					}

					if len(faults) == 0 {
						return errors.New("no fault entries found")
					}
					fault := faults[len(faults)-1]
					r, err := fault.Open()
					if err != nil {
						return err
					}
					if _, err = io.Copy(os.Stdout, r); err != nil {
						_ = r.Close()
						return err
					}
					fmt.Println()
					if err = r.Close(); err != nil {
						return err
					}

					log.Printf("faulting cure terminated %s ago", time.Since(fault.Time()))
					return fault.Destroy()
				}
			},
		).Flag(
			&flagDump,
			"dump", command.StringFlag(""),
			"Write IR to specified pathname and terminate",
		).Flag(
			&flagExport,
			"export", command.StringFlag(""),
			"Export cured artifact to specified pathname",
		).Flag(
			&flagEnter,
			"enter", command.BoolFlag(false),
			"Enter cure container with an interactive shell",
		).Flag(
			&flagRemote,
			"daemon", command.BoolFlag(false),
			"Cure artifact on the daemon",
		).Flag(
			&flagNoReply,
			"no-reply", command.BoolFlag(false),
			"Do not receive a reply from the daemon",
		).Flag(
			&flagBoot,
			"boot", command.BoolFlag(false),
			"Build on the stage0 toolchain",
		).Flag(
			&flagStd,
			"std", command.BoolFlag(false),
			"Build on the intermediate toolchain",
		).Flag(
			&flagFaults,
			"faults", command.BoolFlag(false),
			"Display fault entries of the specified artifact",
		).Flag(
			&flagPop,
			"pop", command.BoolFlag(false),
			"Display and destroy the most recent fault entry",
		).Flag(
			&flagRebuild,
			"rebuild", command.BoolFlag(false),
			"Always enter the artifact implementation",
		)
	}

	c.NewCommand(
		"validate",
		"Repeatedly cure named artifact to validate determinism",
		func(args []string) error {
			stage := rosa.Std
			if len(args) == 3 {
				switch args[0] {
				case "boot":
					stage -= 2
				case "std":
					stage -= 1

				default:
					return fmt.Errorf("invalid stage %q", args[0])
				}
				args = args[1:]
			}

			if len(args) != 2 {
				return errors.New("validate requires 2 arguments")
			}

			n, err := strconv.Atoi(args[0])
			if err != nil {
				return fmt.Errorf("invalid passes %q", args[0])
			}

			if n < 2 {
				return errors.New("validate must rebuild at least twice")
			}

			_, a := rosa.Native().New(stage).Load(rosa.ArtifactH(unique.Make(args[1])))
			if a == nil {
				return fmt.Errorf("unknown artifact %q", args[1])
			}

			if !a.IsExclusive() && cm.attr.Jobs < 1 {
				cm.attr.Jobs = runtime.NumCPU()/n + 1
			}

			res := make([]unique.Handle[pkg.Checksum], n)
			if err = cm.Do(func(cache *pkg.Cache) error {
				errs := make([]error, n)
				var wg sync.WaitGroup
				for i := range n {
					wg.Go(func() {
						_, res[i], errs[i] = cache.CureNew(a)
					})
				}
				wg.Wait()
				return errors.Join(errs...)
			}); err != nil {
				return err
			}

			for i := range n - 1 {
				if res[i] == res[i+1] {
					continue
				}

				var buf strings.Builder
				buf.WriteString("nondeterminism:")
				for _, o := range res {
					buf.WriteString("\n\t")
					buf.WriteString(filepath.Join(
						cm.base,
						"checksum",
						pkg.Encode(o.Value()),
					))
				}
				return errors.New(buf.String())
			}
			return nil
		},
	)

	cleanC := c.New("clean", "Remove unused entries from the cache")
	cleanC.NewCommand(
		"fault",
		"Remove all fault entries from the cache",
		func([]string) error {
			return cm.Do(func(*pkg.Cache) error {
				pathname := filepath.Join(cm.base, "fault")
				dents, err := os.ReadDir(pathname)
				if err != nil {
					return err
				}

				for _, dent := range dents {
					msg.Verbosef("destroying entry %s", dent.Name())
					if err = os.Remove(filepath.Join(pathname, dent.Name())); err != nil {
						return err
					}
				}
				log.Printf("destroyed %d fault entries", len(dents))
				return nil
			})
		},
	)
	cleanC.NewCommand(
		"checksum",
		"Remove unreachable checksum entries",
		func([]string) error {
			return cm.Do(func(cache *pkg.Cache) error {
				_, checksums, err := cache.Clean(flagDry, false)
				log.Printf("destroyed %d entries", len(checksums))
				return err
			})
		},
	)
	{
		var flagDeep bool
		cleanC.NewCommand(
			"all",
			"Remove identifiers not reachable by loaded packages",
			func([]string) error {
				return cm.Do(func(cache *pkg.Cache) error {
					t := rosa.Native().Clone().Std()
					handles := t.CollectAll()

					flags := t.Flags()
					a := t.Append(nil, handles...)
					for arch := range rosa.Arches(nil) {
						if arch == runtime.GOARCH {
							continue
						}

						t.DropCaches(arch, rosa.OptLLVMNoLTO|rosa.OptSkipCheck)
						a = t.Append(a, handles...)
						t.DropCaches(arch, flags)
						a = t.Append(a, handles...)
					}

					ids, checksums, err := cache.Clean(
						flagDry,
						!flagDeep,
						a...,
					)
					log.Printf(
						"destroyed %d identifier and %d checksum entries",
						len(ids), len(checksums),
					)
					return err
				})
			},
		).Flag(
			&flagDeep,
			"deep", command.BoolFlag(false),
			"Include transitive inputs",
		)
	}

	c.NewCommand(
		"abort",
		"Abort all pending cures on the daemon",
		func([]string) error { return abortRemote(ctx, &addr, false) },
	)

	{
		var (
			flagNet     bool
			flagSession bool

			flagWithToolchain bool
		)
		c.NewCommand(
			"shell",
			"Interactive shell in the specified Rosa OS environment",
			func(args []string) error {
				resolvconf := "nameserver 1.1.1.1\nnameserver 1.0.0.1\n"
				if p, err := os.ReadFile(fhs.AbsEtc.Append(
					"resolv.conf",
				).String()); err != nil {
					if !errors.Is(err, os.ErrNotExist) {
						return err
					}
				} else {
					resolvconf = unsafe.String(unsafe.SliceData(p), len(p))
				}

				handles := make([]rosa.ArtifactH, len(args), len(args)+3)
				for i, arg := range args {
					handles[i] = rosa.ArtifactH(unique.Make(arg))
					if meta, _ := rosa.Native().Std().Load(handles[i]); meta == nil {
						return fmt.Errorf("unknown artifact %q", arg)
					}
				}

				base := rosa.H("llvm")
				if !flagWithToolchain {
					base = rosa.H("musl")
				}
				handles = append(handles,
					base,
					rosa.H("mksh"),
					rosa.H("toybox"),
				)

				root := make(pkg.Collect, 0, 6+len(args))
				root = append(root, rosa.NewEtc(false))
				root = rosa.Native().Std().Append(root, handles...)

				return cm.Do(func(cache *pkg.Cache) error {
					return cache.EnterExec(
						ctx,
						pkg.NewExec(
							"",
							rosa.Native().Arch(),
							new(pkg.Checksum),
							1,
							flagNet,
							false,
							fhs.AbsRoot,
							[]string{
								"SHELL=/system/bin/mksh",
								"PATH=/system/bin",
								"HOME=/",
							},
							fhs.AbsProc.Append("nonexistent"),
							nil,
							pkg.Path(fhs.AbsRoot, true, root...),
							pkg.Path(
								fhs.AbsEtc.Append("resolv.conf"), false,
								pkg.NewFile(
									"resolv.conf",
									unsafe.Slice(unsafe.StringData(resolvconf), len(resolvconf)),
								),
							),
						),
						"localhost",
						flagSession, os.Stdin, os.Stdout, os.Stderr,
						rosa.AbsSystem.Append("bin", "mksh"),
						"sh",
					)
				})
			},
		).Flag(
			&flagNet,
			"net", command.BoolFlag(false),
			"Share host net namespace",
		).Flag(
			&flagSession,
			"session", command.BoolFlag(true),
			"Retain session",
		).Flag(
			&flagWithToolchain,
			"with-toolchain", command.BoolFlag(false),
			"Include the stage2 LLVM toolchain",
		)
	}

	c.Command(
		"help",
		"Show this help message",
		func([]string) error { c.PrintHelp(); return nil },
	)

	c.MustParse(os.Args[1:], func(err error) {
		cm.Close()
		if w, ok := err.(interface{ Unwrap() []error }); !ok {
			log.Fatal(err)
		} else {
			errs := w.Unwrap()
			for i, e := range errs {
				if i == len(errs)-1 {
					log.Fatal(e)
				}
				log.Println(e)
			}
		}
	})
}
