FROM eclipse-temurin:17-jdk AS build
WORKDIR /app

COPY . /app
RUN ./gradlew clean build -x test
RUN mkdir -p build/dependency && (cd build/dependency; jar -xf ../libs/*-SNAPSHOT.jar)

FROM eclipse-temurin:17-jdk


# Keeps Python from generating .pyc files in the container
ENV PYTHONDONTWRITEBYTECODE=1

# Turns off buffering for easier container logging
ENV PYTHONUNBUFFERED=1

# Install dependencies needed to run OCCMD tool
# file is needed by https://github.com/fkie-cad/fact_helper_file
RUN apt-get update && \
    apt-get install -y --no-install-recommends \
    git \
    python3 \
    python3-dev \
    python3-pip \
    libmagic1 \
    gcc  \
    wget  \
    file && \
    rm -rf /var/lib/apt/lists/*

WORKDIR /bin
RUN wget 								\
	https://github.com/XAMPPRocky/tokei/releases/download/v13.0.0-alpha.0/tokei-x86_64-unknown-linux-musl.tar.gz \
	-O - 								| \
	tar zxf -							&& \
	which tokei

# The base distro for eclipse-temurin doesn't have the newest pip version
# which causes weired errors so we upgrade pip.
RUN pip install --upgrade pip

WORKDIR /occmd
# Download occmd
RUN git clone 								\
	--depth 1 							\
	--single-branch --branch main 					\
	https://gitlab.opencode.de/opencode-analyzer/occmd-public	\
	/occmd
RUN git submodule update --init --recursive

RUN pip3 install -r ./requirements.txt

COPY tools/occmd/occmdcfg.ini .

# Optional: avoid cloning blacklist on each run
WORKDIR /occmd/resources/checks/checked_in_binaries/blacklist
RUN git clone \
--depth 1 \
https://gitlab.opencode.de/opencode-analyzer/occmd-checked_in_binaries-blacklist \
/app/resources/checks/checked_in_binaries/blacklist

WORKDIR /app
RUN mkdir -p /app/git
VOLUME /tmp

ARG DEPENDENCY=/app/build/dependency
COPY --from=build ${DEPENDENCY}/BOOT-INF/lib /app/lib
COPY --from=build ${DEPENDENCY}/META-INF /app/META-INF
COPY --from=build ${DEPENDENCY}/BOOT-INF/classes /app

# User creation so we don't need to run the image with the root user
ARG UID=1001
ARG GID=1002

RUN addgroup --system --gid $GID app \
    && adduser --system --uid $UID --gid $GID appuser --no-create-home --home /nonexistent
RUN chown -R appuser:app /occmd /app

# Workaround until OCCMD tool is included into CI/CD
RUN chmod u+x /app/scripts/occmd.sh
USER $UID

ENTRYPOINT ["java","-cp","/app:/app/lib/*","de.fraunhofer.iem.dataprovider.DataProviderApplicationKt"]