# Stage 1: Build Stage
FROM docker:dind as build-stage

# Install necessary build tools and dependencies
RUN apk update && apk add --no-cache \
  git \
  openssl \
  openssl-dev \
  ca-certificates \
  bash \
  curl \
  make \
  gcc \
  g++ \
  python3 \
  python3-dev \
  py3-pip \
  linux-headers \
  paxctl \
  libgcc \
  libstdc++ \
  gnupg \
  nodejs-current \
  npm \
  krb5-libs \
  rust \
  docker-cli \
  libffi-dev \
  libc-dev \
  docker-compose \
  libc6-compat \
  alpine-sdk \
  && update-ca-certificates

# Ensure Python is correctly installed and upgrade pip
ENV PYTHONUNBUFFERED=1
RUN ln -sf python3 /usr/bin/python && \
  apk add --no-cache py3-pip py3-setuptools

# Add the patch fix
COPY ./stack-fix.c /lib/

# Install pnpm
ENV PNPM_HOME="/root/.local/share/pnpm"
RUN mkdir -p ${PNPM_HOME}
ENV PATH="$PNPM_HOME:$PATH"
RUN curl -fsSL "https://github.com/pnpm/pnpm/releases/latest/download/pnpm-linuxstatic-x64" -o /bin/pnpm && chmod +x /bin/pnpm

# Prepare the libraries packages
RUN set -ex \
    && apk add --no-cache --virtual .build-deps build-base \
    && gcc -shared -fPIC /lib/stack-fix.c -o /lib/stack-fix.so \
    && apk del .build-deps

# Export the environment variable of LD_PRELOAD
ENV LD_PRELOAD /lib/stack-fix.so

# Validate installations
RUN node -v && npm -v && pnpm -v
RUN pnpm config set unsafe-perm true

# Stage 2: Final Stage
FROM docker:dind

# Copy necessary files from build-stage
COPY --from=build-stage /usr/bin/python3 /usr/bin/python3
COPY --from=build-stage /usr/lib/python3.*/ /usr/lib/python3.*/
COPY --from=build-stage /usr/bin/pip3 /usr/bin/pip3
COPY --from=build-stage /lib/stack-fix.so /lib/stack-fix.so
COPY --from=build-stage /bin/pnpm /bin/pnpm
COPY --from=build-stage ${PNPM_HOME} ${PNPM_HOME}

# Ensure CA certificates are up-to-date
RUN apk update && apk add --no-cache \
  git \
  openssl \
  openssl-dev \
  ca-certificates \
  bash \
  curl \
  make \
  gcc \
  g++ \
  python3 \
  python3-dev \
  py3-pip \
  linux-headers \
  paxctl \
  libgcc \
  libstdc++ \
  gnupg \
  nodejs-current \
  npm \
  krb5-libs \
  rust \
  docker-cli \
  libffi-dev \
  libc-dev \
  docker-compose \
  libc6-compat \
  alpine-sdk \
  && update-ca-certificates

# Re-set environment variables for final stage
ENV PYTHONUNBUFFERED=1
ENV PNPM_HOME="/root/.local/share/pnpm"
ENV PATH="$PNPM_HOME:$PATH"
ENV LD_PRELOAD /lib/stack-fix.so

# Validate installations in final stage
RUN node -v && npm -v && pnpm -v

RUN pnpm config set unsafe-perm true