load("@aspect_bazel_lib//lib:copy_file.bzl", "copy_file")
load("@aspect_bazel_lib//lib:copy_to_directory.bzl", "copy_to_directory")
load("@rules_pkg//:pkg.bzl", "pkg_tar")
load("//bazel/mkosi:mkosi_image.bzl", "mkosi_image")

copy_to_directory(
    name = "rpms",
    srcs = [
        "@kernel//file",
        "@kernel_core//file",
        "@kernel_modules//file",
        "@kernel_modules_core//file",
    ],
    include_external_repositories = ["kernel*"],
    replace_prefixes = {"file": ""},
)

[
    copy_file(
        name = name,
        src = "@" + name + "//file",
        out = name + ".rpm",
        allow_symlink = True,
    )
    for name in [
        "kernel",
        "kernel_core",
        "kernel_modules",
        "kernel_modules_core",
    ]
]

mkosi_image(
    name = "base",
    srcs = [
        "mkosi.postinst",
        "mkosi.prepare",
    ] + glob([
        "mkosi.skeleton/**",
    ]),
    outs = [
        "image",
        "image.tar",
        "image-.rpm.lock",
        "image-packagemanifest",
        "image-rpmdb.sqlite",
        "image-rpmdb.sqlite-shm",
        "image-rpmdb.sqlite-wal",
    ],
    extra_trees = [
        "//image:sysroot_tar",
        "//image:cryptsetup_closure",
    ],
    local_mirror = ["@mkosi_rpms//:repo"],
    mkosi_conf = "mkosi.conf",
    package_files = [
        ":kernel",
        ":kernel_core",
        ":kernel_modules",
        ":kernel_modules_core",
    ],
    tags = [
        "manual",
        "no-cache",
    ],
    visibility = ["//visibility:public"],
)

pkg_tar(
    name = "rpmdb",
    srcs = [
        "image-.rpm.lock",
        "image-packagemanifest",
        "image-rpmdb.sqlite",
        "image-rpmdb.sqlite-shm",
        "image-rpmdb.sqlite-wal",
    ],
    remap_paths = {
        "/image-.rpm.lock": "/var/lib/rpm/.rpm.lock",
        "/image-packagemanifest": "/usr/share/constellation/packagemanifest",
        "/image-rpmdb.sqlite": "/var/lib/rpm/rpmdb.sqlite",
        "/image-rpmdb.sqlite-shm": "/var/lib/rpm/rpmdb.sqlite-shm",
        "/image-rpmdb.sqlite-wal": "/var/lib/rpm/image-rpmdb.sqlite-wal",
    },
    tags = ["manual"],
    visibility = ["//visibility:public"],
)
