ARG REPO_LOCATION

FROM ${REPO_LOCATION}minideb AS builder

RUN install_packages git curl openssh-client ca-certificates

RUN echo "deb [arch=armhf] http://download.docker.com/linux/debian buster stable" >/etc/apt/sources.list.d/docker.list
RUN curl -fsSL https://download.docker.com/linux/debian/gpg >/etc/apt/trusted.gpg.d/docker.asc

COPY imagewrangler_ed25519 /tmp/imagewrangler_ed25519
RUN ssh-keyscan -H git.starbeamrainbowlabs.com >/tmp/known_hosts

# Invalidate the cache to force Docker to pull the latest commit
ADD datetime.txt /tmp/datetime.txt
RUN GIT_SSH_COMMAND="ssh -i /tmp/imagewrangler_ed25519 -o PreferredAuthentications=publickey -o UserKnownHostsFile=/tmp/known_hosts" git clone git@git.starbeamrainbowlabs.com:sbrl/cluster-config.git /srv
WORKDIR /srv
RUN git submodule update --init

###############################################################################

FROM ${REPO_LOCATION}minideb

# Docker apt repo
COPY --from=builder /etc/apt/trusted.gpg.d/docker.asc /etc/apt/trusted.gpg.d/docker.asc
COPY --from=builder /etc/apt/sources.list.d/docker.list /etc/apt/sources.list.d/docker.list

# Everything from make onwards is needed for minideb
RUN install_packages curl jq docker-ce-cli ca-certificates fakeroot fakechroot git

# These will probably invalidate the cache, so we install the packages above first
COPY --from=builder /srv/lantern-build-engine /srv/lantern-build-engine
COPY --from=builder /srv/docker /srv/docker
COPY --from=builder /srv/scripts /srv/scripts

# Note that we chown here because COPY --chown is apparently unreliable :-(
RUN groupadd --gid 995 docker && \
	useradd --no-create-home --system --uid 50 --groups docker imagewrangler && \
	chown -R 50:995 /srv/docker && \
	mkdir /mnt/data_dir

# We need the docker socket to enable us to start containers in order to check them
VOLUME /run/docker.sock
VOLUME /mnt/data_dir

# 995 = the docker group on docker.sock
USER imagewrangler:docker

WORKDIR /srv/scripts
ENTRYPOINT [ "/bin/bash", "./imagewrangler.sh", "check" ]