
# build/make inside a container
#
ARG BASE_BUILDER_IMAGE
ARG BASE_RUNNER_IMAGE
ARG py_src_repo=$BASE_BUILDER_IMAGE

FROM ${py_src_repo} as builder
ARG build_root=/build/nsx-pace/pace/nta/detectors
ARG proto_dir=${build_root}/../../../proto3
ARG DETECTOR_NAME

# change user to allow tool install for buidler
USER root

# install build tools in container
RUN apt-get -y install make

# setup build root dir
RUN mkdir -p ${build_root} && mkdir -p ${proto_dir}
COPY . ${build_root}

WORKDIR ${build_root}

# install requirements
RUN pip3 install -r common/requirements.txt -r ${DETECTOR_NAME}/requirements.txt

# Build the proto, openapi models, & run test
# note: we didn't need to call 'proto-cache' since the 'outer' makefile already call
#       'proto-cache' that copies the proto file to nta/detector. docker build will
#       automatically pick up the proto-cache as build context
# note: same mechanism applies for openapi
RUN make proto && make openapi && make test-common && make test-llmnrnbtns

# for debugging
# RUN touch build.done

#
# prepare the final image
#
FROM $BASE_RUNNER_IMAGE
ARG build_root=/build/nsx-pace/pace/nta/detectors
ARG run_root=/opt/vmware/nsx/intelligence/nta/detectors
ARG DETECTOR_NAME

# Setup ENV for docker image
#   this would be replace by helm later
ENV PYTHONPATH=${run_root}

RUN mkdir -p ${run_root}

# copy from builder into final image
#   copy the py file from builder to the image (same directory structure)
COPY --from=builder ${build_root}/common ${run_root}/common
COPY --from=builder ${build_root}/vmware ${run_root}/vmware
COPY --from=builder ${build_root}/openapi ${run_root}/openapi
COPY --from=builder ${build_root}/${DETECTOR_NAME} ${run_root}/${DETECTOR_NAME}

#
# root priv section
#   If you want to execute any root priv opt (e.g. apt-get to install new pkg
#   do it between the "root priv section"
#

# change user to allow us to setup install new tools
USER root

ENV HOME=/
ENV HOME_DIR=/home/vmware/
RUN pip3 install -r ${run_root}/common/requirements.txt -r ${run_root}/${DETECTOR_NAME}/requirements.txt

# change user back to 1001 (vmware)
USER 1001

#
# End root priv section
#

# run the detector
CMD cd /opt/vmware/nsx/intelligence/nta/detectors && python3 llmnrnbtns/detector/main.py

# for debugging
# RUN touch ${run_root}/image.done
