FROM golang:1.25-alpine AS builder
ENV KNOT_REPO_SCAN_PATH=/home/git/repositories
ENV CGO_ENABLED=1

ARG TAG='v1.13.0-alpha'

WORKDIR /app
RUN apk add git gcc musl-dev
RUN git clone -b ${TAG} https://tangled.org/tangled.org/core .

FROM builder AS build-knot
RUN go build -o /usr/bin/knot -ldflags '-s -w -extldflags "-static"' ./cmd/knot

FROM builder AS build-spindle
RUN go build -o /usr/bin/spindle -ldflags '-s -w -extldflags "-static"' ./cmd/spindle

FROM alpine:latest AS knot
EXPOSE 5555
EXPOSE 22

LABEL org.opencontainers.image.title='knot'
LABEL org.opencontainers.image.description='data server for tangled'
LABEL org.opencontainers.image.source='https://tangled.org/sachy.dev/knot-spindle-docker'
LABEL org.opencontainers.image.url='https://tangled.org'
LABEL org.opencontainers.image.vendor='tangled.org'
LABEL org.opencontainers.image.licenses='MIT'

ARG UID=1000
ARG GID=1000

COPY rootfs .
RUN chmod 755 /etc
RUN chmod -R 755 /etc/s6-overlay
RUN apk add shadow s6-overlay execline openssl openssh git curl bash
RUN groupadd -g $GID -f git
RUN useradd -u $UID -g $GID -d /home/git git
RUN openssl rand -hex 16 | passwd --stdin git
RUN mkdir -p /home/git/repositories && chown -R git:git /home/git
COPY --from=build-knot /usr/bin/knot /usr/bin
RUN mkdir /app && chown -R git:git /app

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

ENTRYPOINT ["/init"]

FROM alpine:latest AS spindle

EXPOSE 6555

LABEL org.opencontainers.image.title="spindle"
LABEL org.opencontainers.image.description="ci server for tangled"
LABEL org.opencontainers.image.source="https://tangled.org/sachy.dev/knot-spindle-docker"
LABEL org.opencontainers.image.url="https://tangled.org"
LABEL org.opencontainers.image.vendor="tangled.org"
LABEL org.opencontainers.image.licenses="MIT"

ARG UID=1000
ARG GID=1000

RUN adduser --system --uid $UID spindle
RUN addgroup --system --gid $UID spindle
RUN mkdir -p /app && chown -R spindle:spindle /app
COPY --from=build-spindle /usr/bin/spindle /usr/bin

WORKDIR /app
CMD ["spindle"]
VOLUME ["/app"]
HEALTHCHECK --interval=60s --timeout=30s --start-period=5s --retries=3 \
    CMD curl -f http://localhost:6555 || exit 1
