FROM ubuntu:24.04 as ubuntu2404
ARG TARGETARCH
ARG OS_RELEASE=lunar
ARG DIR=ubuntu-24.04-${TARGETARCH}-debs
ARG PKGS=.common[],.debs[],.ubuntu[],.ubuntu2404[]
ARG BUILD_TOOLS="apt-transport-https software-properties-common ca-certificates curl wget gnupg dpkg-dev genisoimage"
ENV DEBIAN_FRONTEND=noninteractive

# dump system package list
RUN dpkg --get-selections | grep -v deinstall | cut -f1 | cut -d ':' -f1 > packages.list
RUN apt update -qq \
    && apt install -y --no-install-recommends $BUILD_TOOLS \
    && curl -fsSL "https://download.docker.com/linux/ubuntu/gpg" | apt-key add -qq - \
    && echo "deb [arch=$TARGETARCH] https://download.docker.com/linux/ubuntu ${OS_RELEASE} stable" > /etc/apt/sources.list.d/docker.list \
    && apt update -qq

WORKDIR /package
COPY packages.yaml .

COPY --from=mikefarah/yq:4.11.1 /usr/bin/yq /usr/bin/yq
RUN yq eval "${PKGS}" packages.yaml >> packages.list \
    && sort -u packages.list | xargs apt-get install --yes --reinstall --print-uris | awk -F "'" '{print $2}' | grep -v '^$' | sort -u > packages.urls

RUN mkdir -p ${DIR} \
    && wget -q -x -P ${DIR} -i packages.urls \
    && cd ${DIR} \
    && dpkg-scanpackages ./ /dev/null | gzip -9c > ./Packages.gz

RUN genisoimage -r -o ${DIR}.iso ${DIR}

FROM scratch
COPY --from=ubuntu2404 /package/*.iso /
