ARG BUILDER_IMAGE=golang:1.26-alpine
ARG DEPLOY_IMAGE=alpine:edge
FROM ${BUILDER_IMAGE} as builder
ENV KNOT_REPO_SCAN_PATH=/home/git/repositories
ENV CGO_ENABLED=1 GOSUMDB=off GOPROXY=direct

ARG KNOT_RELEASE_TAG='v1.14.1-alpha' KNOT_REPO_URL=https://tangled.org/@tangled.org/core

WORKDIR /app
RUN apk add git gcc musl-dev
RUN git clone -b ${KNOT_RELEASE_TAG} ${KNOT_REPO_URL} . \
    && go build -o /usr/bin/knot -ldflags '-s -w -extldflags "-static"' ./cmd/knot \
    && git rev-parse HEAD > commit-sha.txt

FROM ${DEPLOY_IMAGE} as deploy
EXPOSE 5555
EXPOSE 22

ARG DOCKER_BUILD_COMMIT
ARG DOCKER_BUILD_REPO=https://gitlab.com/recaptime-dev/infra/docker/tangled-knotserver

LABEL org.opencontainers.image.title='Knot data server for Tangled (Recap Time Squad image distribution)' \
    org.opencontainers.image.description="Tangled's data server for hosting Git repositories in the Atmosphere" \
    org.opencontainers.image.source=${DOCKER_BUILD_REPO} \
    org.opencontainers.image.url='https://tangled.org' \
    org.opencontainers.image.vendor='Recap Time Squad' \
    org.opencontainers.image.authors="Andrei Jiroh Halili <ajhalili2006@crew.recaptime.dev>" \
    org.opencontainers.image.licenses='MIT' \
    org.opencontainers.image.revision=${DOCKER_BUILD_COMMIT} \
    org.opencontainers.image.documentation='https://docs.tangled.org/knot-self-hosting-guide.html'

ENV TANGLED_REPO_URL=${KNOT_REPO_URL} \
    DOCKER_BUILD_COMMIT=${DOCKER_BUILD_COMMIT} \
    DOCKER_BUILD_REPO=${DOCKER_BUILD_REPO} \
    KNOT_REPO_SCAN_PATH=/home/git/repositories

ARG UID=2897
ARG GID=2897

COPY rootfs .
COPY motd.txt /home/git/motd

RUN chmod 755 /etc && chmod -R 755 /etc/s6-overlay \
    && apk add shadow s6-overlay execline openssl openssh git curl bash \
    && groupadd -g $GID -f git \
    && useradd -u $UID -g $GID -d /home/git git \
    && openssl rand -hex 16 | passwd --stdin git \
    && mkdir -p /home/git/repositories && chown -R git:git /home/git \
    && mkdir /app && chown -R git:git /app \
    && chown git:git /home/git/motd

COPY --from=builder /usr/bin/knot /usr/bin
COPY --from=builder /app/commit-sha.txt /opt/knotserver-commit-sha

HEALTHCHECK --interval=60s --timeout=30s --start-period=5s --retries=3 \
    CMD curl -f http://localhost:5555 || exit 1

ENTRYPOINT ["/init"]
