FROM python:3.7-buster AS builder

###########################################################
# Install dependencies
WORKDIR /usr/src/cue

# Add stash to known_hosts, so pip installing via git doesn't fail.
RUN mkdir -p /root/.ssh \
  && chmod 0700 /root/.ssh \
  && ssh-keyscan -p 12051 gitlab-master.nvidia.com > /root/.ssh/known_hosts

COPY requirements-dev.txt ./

ARG ssh_prv_key
ARG ssh_pub_key

# In one step: Import SSH keys from host, use them to pull stash-hosted
# dependencies, and then delete the SSH keys.
# This needs to be a single step to prevent docker from creating a layer that
# has someone's private/public SSH keys on them.
RUN echo "$ssh_prv_key" > /root/.ssh/id_rsa \
  && echo "$ssh_pub_key" > /root/.ssh/id_rsa.pub \
  && chmod 600 /root/.ssh/id_rsa \
  && chmod 600 /root/.ssh/id_rsa.pub \
  && pip install --no-cache-dir -r requirements-dev.txt \
  && rm -rf /root/.ssh/

###########################################################
# Build the openapi.json for cue_v1
COPY cue cue
COPY cue_cue_v1 cue_cue_v1

# HACK: It's hard to build the OpenAPI specs without importing EVERYTHING.
#       Since we don't want to copy over any more than necessary, we'll build
#       the cue_v1 spec in a more direct way.
RUN { \
  echo 'from core.infra.cue.tests.fixtures import specs'; \
  echo 'name = "cue_cue_v1"'; \
  echo 'spec = specs._build_openapi_spec(name)'; \
  echo 'specs._save_openapi_json(name, spec, "openapi.json")'; \
} | python

###########################################################
# Collect the information about the helptext tree
COPY cli_cue cli_cue
COPY scripts/spider/spider_lib.py ./
COPY scripts/spider/spider_collect.py ./

RUN python spider_collect.py -o ./collected.json

###########################################################
# Render the collected information
COPY scripts/spider/spider_render.py ./
COPY scripts/spider/templates ./templates
COPY scripts/spider/datafiles ./datafiles

RUN python spider_render.py --input ./collected.json -o /html

###########################################################
# Create an nginx container with the rendered HTML files
FROM nginx:alpine

COPY --from=builder /html /usr/share/nginx/html
COPY scripts/shared /usr/share/nginx/html/shared
COPY scripts/spider/nginx/default.conf /etc/nginx/conf.d/default.conf
