package main

import (
	"fmt"
	"time"

	"golang.org/x/sys/unix"
)

// Running as PID 1 there is nothing underneath us: sysfs and devtmpfs are what
// every check, counter and device node below is reached through, and no one
// else is going to mount them. Written as checks like everything else, so this
// is a silent no-op under a running system.

type mountSpec struct {
	dir    string
	fstype string
	magic  int64
	flags  uintptr
}

var wantMounts = []mountSpec{
	{"/proc", "proc", unix.PROC_SUPER_MAGIC, unix.MS_NOSUID | unix.MS_NODEV | unix.MS_NOEXEC},
	{"/sys", "sysfs", unix.SYSFS_MAGIC, unix.MS_NOSUID | unix.MS_NODEV | unix.MS_NOEXEC},
	// devtmpfs reports itself as tmpfs, which is why the magic alone is not
	// enough to tell it apart from the directory it would be mounted over.
	{"/dev", "devtmpfs", unix.TMPFS_MAGIC, unix.MS_NOSUID},
}

// Whether something is mounted here, as opposed to this being a plain
// directory on whatever filesystem contains it. The type alone cannot answer
// that: booted from an initramfs the root is itself tmpfs, so an empty /dev
// directory on it is indistinguishable by magic from a mounted devtmpfs.
func isMountRoot(dir string) (bool, error) {
	var stx unix.Statx_t
	if err := unix.Statx(unix.AT_FDCWD, dir, 0, unix.STATX_BASIC_STATS, &stx); err != nil {
		return false, err
	}
	if stx.Attributes_mask&unix.STATX_ATTR_MOUNT_ROOT == 0 {
		return false, fmt.Errorf("kernel does not report STATX_ATTR_MOUNT_ROOT")
	}
	return stx.Attributes&unix.STATX_ATTR_MOUNT_ROOT != 0, nil
}

func checkMount(m mountSpec) checkResult {
	res := checkResult{item: "mount " + m.dir}
	var st unix.Statfs_t
	err := unix.Statfs(m.dir, &st)
	if err == unix.ENOENT {
		if err := unix.Mkdir(m.dir, 0o755); err != nil {
			res.err = fmt.Errorf("creating %s: %w", m.dir, err)
			return res
		}
		err = unix.Statfs(m.dir, &st)
	}
	if err != nil {
		res.err = err
		return res
	}
	mounted, err := isMountRoot(m.dir)
	if err != nil {
		res.err = err
		return res
	}
	if mounted && int64(st.Type) == m.magic {
		res.state = m.fstype + " already mounted"
		return res
	}
	if err := unix.Mount(m.fstype, m.dir, m.fstype, m.flags, ""); err != nil {
		res.err = err
		return res
	}
	res.fixed = true
	res.state = "mounted " + m.fstype
	return res
}

// Each mount is what the next check stands on, so the first failure ends it.
func mountFilesystems() []checkResult {
	var out []checkResult
	for _, m := range wantMounts {
		res := checkMount(m)
		out = append(out, res)
		if res.err != nil {
			return out
		}
	}
	return out
}

const (
	touchTimeout = 30 * time.Second
	touchPoll    = 100 * time.Millisecond
)

// USB enumerates asynchronously and the kernel hands us control long before the
// bus has settled, so unlike everything else here the touchscreen is genuinely
// not there yet rather than absent. It is the only device we wait for.
func waitForTouchscreen() checkResult {
	res := checkResult{item: "touchscreen"}
	start := time.Now()
	for {
		f, err := findTouchscreen()
		if err == nil {
			f.Close()
			waited := time.Since(start)
			if waited < touchPoll {
				res.state = "ready"
				return res
			}
			res.fixed = true
			res.state = fmt.Sprintf("ready after %.1fs", waited.Seconds())
			return res
		}
		if time.Since(start) >= touchTimeout {
			res.err = fmt.Errorf("%w after %s", err, touchTimeout)
			return res
		}
		time.Sleep(touchPoll)
	}
}

func bootstrap() []checkResult {
	out := mountFilesystems()
	// /dev/input/event* only exists once devtmpfs is mounted above.
	if out[len(out)-1].err != nil {
		return out
	}
	return append(out, waitForTouchscreen())
}
