package main

import (
	"context"
	"errors"
	"os"
	"path/filepath"
	"strconv"
	"syscall"
	"time"

	"hakurei.app/check"
	"hakurei.app/fhs"
	"hakurei.app/internal/kobject"
	"hakurei.app/internal/uevent"
)

// mustMountSystem waits for and mounts a system device matching pattern.
func mustMountSystem(
	ctx context.Context,
	s *kobject.State,
	pattern string,
) {
	c, stop := context.WithTimeout(ctx, 30*time.Second)
	defer stop()

	for {
		var matchErr error
		var systemPath *check.Absolute
		s.Range(c, func(o *kobject.Object, act uevent.KobjectAction) bool {
			if (act != uevent.KOBJ_ADD && act != uevent.KOBJ_CHANGE) ||
				o.Subsystem != "block" ||
				o.Env["DEVTYPE"] != "disk" {
				return true
			}

			if ok, err := filepath.Match(pattern, o.DevPath); err != nil {
				matchErr = err
				return false
			} else if !ok {
				return true
			}

			name, ok := o.Env["DEVNAME"]
			if !ok {
				return true
			}
			systemPath = fhs.AbsDev.Append(name)
			return false
		})
		if c.Err() != nil {
			fatal("devpath", strconv.Quote(pattern), "never appeared")
		}
		if matchErr != nil {
			fatal("cannot match system devpath:", matchErr)
		}
		err := syscall.Mount(
			systemPath.String(),
			"/system/",
			"squashfs",
			0,
			"threads=multi",
		)
		if err == nil {
			break
		}
		if !errors.Is(err, os.ErrNotExist) {
			fatal("cannot mount system:", err)
		}
	}
}
