# Stage 1: Builder
FROM alpine AS builder

# Get the target platform
ARG TARGETPLATFORM
ENV HAYABUSA_VERSION=3.8.1
ENV TAKAJO_VERSION=2.15.1

# Install necessary tools
RUN apk add --no-cache unzip wget git

# Determine the correct zip files and binaries based on TARGETPLATFORM
RUN \
    case "$TARGETPLATFORM" in \
    "linux/amd64") \
        HAYABUSA_ZIP="hayabusa-${HAYABUSA_VERSION}-lin-x64-gnu.zip"; \
        HAYABUSA_BINARY="hayabusa-${HAYABUSA_VERSION}-lin-x64-gnu"; \
        TAKAJO_ZIP="takajo-${TAKAJO_VERSION}-lin-x64-gnu.zip"; \
        TAKAJO_BINARY="takajo-${TAKAJO_VERSION}-lin-x64-gnu"; \
        ;; \
    "linux/arm64") \
        HAYABUSA_ZIP="hayabusa-${HAYABUSA_VERSION}-lin-aarch64-gnu.zip"; \
        HAYABUSA_BINARY="hayabusa-${HAYABUSA_VERSION}-lin-aarch64-gnu"; \
        ;; \
    *) echo "Unsupported platform: $TARGETPLATFORM"; exit 1 ;; \
    esac && \
    # Download Hayabusa zip
    wget -O /hayabusa.zip "https://github.com/Yamato-Security/hayabusa/releases/download/v${HAYABUSA_VERSION}/${HAYABUSA_ZIP}" && \
    mkdir -p /opt/hayabusa && \
    cd /opt/hayabusa && \
    unzip /hayabusa.zip && \
    ln -s "$HAYABUSA_BINARY" /opt/hayabusa/hayabusa && \
    chmod +x /opt/hayabusa/hayabusa && \
    # Download and extract Takajo for linux/amd64 only
    if [ "$TARGETPLATFORM" = "linux/amd64" ]; then \
        wget -O /takajo.zip "https://github.com/Yamato-Security/takajo/releases/download/v${TAKAJO_VERSION}/${TAKAJO_ZIP}" && \
        unzip /takajo.zip -d /opt/hayabusa && \
        ln -s "$TAKAJO_BINARY" /opt/hayabusa/takajo && \
        chmod +x /opt/hayabusa/takajo; \
    fi

# Clone the latest rules directly from GitHub
RUN rm -rf /opt/hayabusa/rules
RUN git clone --depth=1 https://github.com/Yamato-Security/hayabusa-rules.git /opt/hayabusa/rules

# Stage 2: Final Image
FROM ubuntu

# Copy only the necessary files from the builder stage
COPY --from=builder /opt/hayabusa /opt/hayabusa

# Set environment variables
ENV PATH="${PATH}:/opt/hayabusa"

# Install necessary packages
RUN apt-get update && \
apt-get install -y --no-install-recommends bash libcurl4 libpcre3 libsqlite3-0 && \
rm -rf /var/lib/apt/lists/*

# Set the working directory
WORKDIR /data

# Create output directory
RUN mkdir /output

# Add the startup script
COPY start.sh /root/start.sh
RUN chmod +x /root/start.sh

# Set the default command
CMD ["/bin/bash", "/root/start.sh"]
