# Set the Alpine version for consistency
ARG ALPINE_VERSION=3.20.3

# First stage: Build Kaniko executor
FROM alpine:${ALPINE_VERSION} AS kaniko-build

# Install necessary tools
RUN apk --update --no-cache add skopeo umoci

# Set working directory
WORKDIR /workdir-kaniko

# Specify Kaniko version
ARG KANIKO_VERSION=1.23.2

# Copy Kaniko executor using skopeo
RUN skopeo copy docker://gcr.io/kaniko-project/executor:v${KANIKO_VERSION} oci:kaniko:current

# Unpack the Kaniko executor
RUN umoci unpack --image kaniko:current unpacked

# Second stage: Create the final image
FROM alpine:${ALPINE_VERSION}

# Add a non-root user with UID and GID 1001
RUN addgroup -S kaniko -g 1001 && adduser -S kaniko -u 1001 -G kaniko

# Create necessary directories and set ownership and permissions
RUN mkdir -p /opt/kaniko /kaniko && \
    chown -R kaniko:kaniko /opt/kaniko /kaniko && \
    chmod -R 775 /opt/kaniko /kaniko

# Copy the Kaniko executor from the build stage
COPY --from=kaniko-build /workdir-kaniko/unpacked/rootfs/kaniko/executor /opt/kaniko/kaniko

# Ensure the executor has the correct ownership and execute permissions
RUN chown -R kaniko:kaniko /opt/kaniko/kaniko && \
    chmod +x /opt/kaniko/kaniko

# Set environment variables
ENV PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/opt/kaniko
ENV DOCKER_CONFIG=/opt/kaniko/.docker/

# Switch to the non-root user
USER kaniko

# Define the entrypoint
ENTRYPOINT ["/opt/kaniko/kaniko"]
