ARG ARCH=amd64

# ---------------------------
# Stage 1: Build iptables
# ---------------------------
FROM alpine:3.18 AS build

RUN apk add --no-cache \
    build-base linux-headers \
    bison flex \
    libmnl-dev libnftnl-dev \
    wget tar xz

WORKDIR /build

RUN wget https://www.netfilter.org/projects/iptables/files/iptables-1.8.9.tar.xz \
    && tar xf iptables-1.8.9.tar.xz \
    && cd iptables-1.8.9 \
    && ./configure --prefix=/usr --with-xtlibdir=/lib/xtables --enable-nftables \
    && make \
    && make install DESTDIR=/build/install

# ---------------------------
# Stage 2: Final runtime image
# ---------------------------
FROM alpine:3.18

ENV APP_NAME=orphe-agent \
    CONFIG_DIR=/etc/orphe-agent \
    DB_DIR=/lib/orphe-agent

ARG ARCH
ENV ARCH=$ARCH

RUN apk add --no-cache \
    iproute2 ipset shadow sudo

COPY --from=build /build/install/usr/sbin/iptables-nft /usr/sbin/iptables
COPY --from=build /build/install/usr/sbin/ip6tables-nft /usr/sbin/ip6tables
COPY --from=build /build/install/lib/xtables /lib/xtables

RUN mkdir -p $CONFIG_DIR $DB_DIR

WORKDIR /app
COPY ./bin/${ARCH}/$APP_NAME /app/$APP_NAME

RUN chmod +x /app/$APP_NAME

RUN useradd -m orphe-agent && echo "orphe-agent:orphe-agent" | chpasswd
RUN echo "orphe-agent ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers

COPY entrypoint.sh /app/entrypoint.sh
RUN chmod +x /app/entrypoint.sh
USER root:orphe-agent
ENTRYPOINT ["/app/entrypoint.sh"]
