#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
#

ARG KERNEL_VERSION
ARG PODMOD_VERSION

## Stage 1: Build kernel module
FROM podmod-builder:$PODMOD_VERSION-$KERNEL_VERSION AS builder

ARG ARCH
ARG KERNEL_VERSION
ARG MODULE_VERSION
ARG PODMOD_VERSION
ARG SHA256
ARG UPSTREAM

WORKDIR /tmp

# Download and extract kernel module from upstream
RUN curl -LS $UPSTREAM -o v4l2loopback-$MODULE_VERSION.tar.gz && \
    echo "$SHA256 v4l2loopback-$MODULE_VERSION.tar.gz" | sha256sum -c && \
    tar xzf v4l2loopback-$MODULE_VERSION.tar.gz && \
    rm v4l2loopback-$MODULE_VERSION.tar.gz

# Build kernel module
RUN cd v4l2loopback-$MODULE_VERSION && \
    make -j$(nproc) && \
    make install

## Stage 2: Stage and prepare files for the final image
FROM podmod-runtime:$PODMOD_VERSION-$KERNEL_VERSION AS staging

ARG KERNEL_VERSION
ARG MODULE_VERSION

# Copy kernel module binary from builder stage
COPY --from=builder \
  /tmp/v4l2loopback-$MODULE_VERSION/v4l2loopback.ko \
  /usr/lib/modules/$KERNEL_VERSION/extra/v4l2loopback.ko

# Install runtime dependencies
RUN dnf install -y \
      v4l-utils

# Copy load and unload scripts into image
COPY load unload /usr/local/sbin/
RUN chmod 0755 /usr/local/sbin/*

# Minimize final image size
RUN dnf clean all -y

## Stage 3: Squash generated image layers
FROM scratch
COPY --from=staging / /

# Set default command for container image
CMD /usr/bin/v4l2-ctl
