from rust:1.96.0-alpine as rust

run apk add --no-cache git musl-dev libudev-zero-dev openssl-dev cryptsetup-dev lvm2-dev clang-libs clang-dev

workdir /src
copy . .
run --mount=type=cache,id=novit-rs,target=/usr/local/cargo/registry \
    --mount=type=cache,id=novit-rs-target,sharing=private,target=/src/target \
    RUSTFLAGS="-C target-feature=-crt-static" cargo install --path . --root /dist

# ------------------------------------------------------------------------
from alpine:3.23.4 as system

workdir /system

run . /etc/os-release \
 && wget -O- https://dl-cdn.alpinelinux.org/alpine/v${VERSION_ID%.*}/releases/x86_64/alpine-minirootfs-${VERSION_ID}-x86_64.tar.gz |tar zxv

run apk add --no-cache --update -p . musl libgcc coreutils \
 ethtool iproute2 lvm2 lvm2-extra lvm2-dmeventd udev cryptsetup \
 e2fsprogs lsblk openssl openssh-server wireguard-tools-wg-quick \
 && rm -rf usr/share/apk var/cache/apk etc/motd dev/*

copy etc/sshd_config etc/ssh/sshd_config

copy --from=rust /dist/bin/init /system/init

run mkdir -p bin run var/log; cd bin && for cmd in init-version init-connect bootstrap; do ln -s ../init $cmd; done

# check viability
run chroot . init-version

# ------------------------------------------------------------------------
from alpine:3.23.4 as initrd

copy --from=system /system /system
run cd /system && find * |cpio -H newc -oF /initrd

# ------------------------------------------------------------------------
from debian:stable-backports as initramfs
run apt update && apt install -y erofs-utils

copy --from=system /system /system
run mkfs.erofs \
  -z lzma -C131072 -Efragments,ztailpacking \
  -T0 --all-time --ignore-mtime \
  /initramfs /system

# ------------------------------------------------------------------------
from alpine:3.23.4
copy --from=initrd /initrd /initrd
entrypoint ["base64","/initrd"]

#copy --from=initramfs /initramfs /
#entrypoint ["base64","/initramfs"]
