#
# Based on wiltonsr/opentracker-docker @see https://github.com/wiltonsr/opentracker-docker/tree/main
# ours uses -DWANT_DYNAMIC_ACCESSLIST for incremental whitelist updates via named pipe
#
FROM gcc:14 AS compile-stage

ARG TINI_VERSION=v0.19.0
ADD https://github.com/krallin/tini/releases/download/${TINI_VERSION}/tini-static /tini
RUN chmod +x /tini

RUN apt update ; \
  apt install cvs -y

RUN adduser \
  --system --disabled-login \
  --uid 6969 --group \
  --home /etc/opentracker \
  farmhand

WORKDIR /usr/src



# Run libowfat compilation in separated layer to benefit from docker layer cache
RUN cvs -d :pserver:cvs@cvs.fefe.de:/cvs -z9 co libowfat ; \
  git clone git://erdgeist.org/opentracker ; \
  cd /usr/src/libowfat ; \
  make

# http://erdgeist.org/arts/software/opentracker/#build-instructions
RUN cd /usr/src/opentracker ; \
  # Build opentracker statically to use it in scratch image
  LDFLAGS=-static make \
  FEATURES+=-DWANT_FULLSCRAPE \
  FEATURES+=-DWANT_FULLLOG_NETWORKS \
  FEATURES+=-DWANT_LOG_NUMWANT \
  FEATURES+=-DWANT_MODEST_FULLSCRAPES \
  FEATURES+=-DWANT_SPOT_WOODPECKER \
  FEATURES+=-DWANT_ACCESSLIST_WHITE \
  FEATURES+=-DWANT_DYNAMIC_ACCESSLIST \
   ;\
  bash -c 'mkdir -pv /tmp/stage/{etc/opentracker,bin}' ; \
  cp -v opentracker.conf.sample /tmp/stage/etc/opentracker/opentracker.conf ; \
  # Opentrack configuration file
  sed -ri \
  -e 's!(.*)(tracker.user)(.*)!\2 farmhand!g;' \
  -e 's!(.*)(access.whitelist)(.*)!\2 /etc/opentracker/whitelist!g;' \
  /tmp/stage/etc/opentracker/opentracker.conf ; \
  install -m 755 opentracker.debug /tmp/stage/bin ; \
  make DESTDIR=/tmp/stage BINDIR="/bin" install ; \
  mkfifo /tmp/stage/etc/opentracker/adder.fifo



FROM alpine

COPY --from=compile-stage /tini /
COPY --from=compile-stage /tmp/stage /
COPY --from=compile-stage /etc/passwd /etc/passwd
COPY ./opentracker.conf /etc/opentracker/opentracker.conf

RUN chown -R 6969:6969 /etc/opentracker ; \
  chmod 0664 /etc/opentracker/whitelist ; \
  chmod 0664 /etc/opentracker/adder.fifo

WORKDIR /etc/opentracker


USER 6969
RUN touch /etc/opentracker/whitelist
RUN ls -lash /etc/opentracker/
  
EXPOSE 6969/udp
EXPOSE 6969/tcp

HEALTHCHECK --interval=5s --timeout=3s --retries=5 \
  CMD curl -f http://localhost:6969/stats || exit 1

ENTRYPOINT ["/tini", "--", "/bin/opentracker"]
CMD ["-f", "/etc/opentracker/opentracker.conf"]