namespace QuickSetup {
    private bool is_drm_card_name(string name) {
        if (!name.has_prefix("card") || name.length == 4) {
            return false;
        }

        for (int i = 4; i < name.length; i++) {
            if (name[i] < '0' || name[i] > '9') {
                return false;
            }
        }

        return true;
    }

    // sysfs_root is configurable so tests can use a synthetic sysfs tree.
    public bool is_nouveau_active(string sysfs_root = "/sys") {
        string drm_path = Path.build_filename(sysfs_root, "class", "drm");

        try {
            var drm_directory = Dir.open(drm_path);
            string? entry_name;

            while ((entry_name = drm_directory.read_name()) != null) {
                if (!is_drm_card_name(entry_name)) {
                    continue;
                }

                string driver_link = Path.build_filename(
                    drm_path,
                    entry_name,
                    "device",
                    "driver"
                );

                try {
                    string driver_target = FileUtils.read_link(driver_link);
                    string resolved_target = driver_target;
                    if (!Path.is_absolute(resolved_target)) {
                        resolved_target = Path.build_filename(
                            Path.get_dirname(driver_link),
                            resolved_target
                        );
                    }

                    if (Path.get_basename(driver_target) == "nouveau"
                            && FileUtils.test(resolved_target, FileTest.IS_DIR)) {
                        return true;
                    }
                } catch (FileError error) {
                    // Missing, broken, or unreadable driver links are not active.
                }
            }
        } catch (FileError error) {
            // Systems without a readable DRM sysfs directory need no workaround.
        }

        return false;
    }

    public bool enable_nouveau_renderer_workaround(string sysfs_root = "/sys") {
        if (!is_nouveau_active(sysfs_root)) {
            return false;
        }

        bool renderer_was_set = Environment.get_variable("GSK_RENDERER") != null;

        // This is g_setenv("GSK_RENDERER", "gl", FALSE), preserving overrides.
        if (!Environment.set_variable("GSK_RENDERER", "gl", false)
                || renderer_was_set) {
            return false;
        }

        message("nouveau DRM driver detected; using GTK OpenGL renderer");
        return true;
    }
}
