#
# 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

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}' ; \
  bash -c 'touch /tmp/stage/etc/opentracker/{white,black}list' ; \
  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



FROM alpine

RUN apk add --no-cache curl bash socat libstdc++ libc6-compat nodejs npm
ARG S6_OVERLAY_VERSION=v3.2.0.2


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

WORKDIR /etc/opentracker


## install caddy so we can use basic-auth on the /whitelist endpoint.
## caddy is run via s6-overlay
## we can remove Caddy once kamal-proxy is more mature @see https://github.com/basecamp/kamal-proxy/issues/48
COPY --from=caddy:alpine /usr/bin/caddy /usr/bin/caddy

# EXPOSE 6969/udp
# EXPOSE 6969/tcp
EXPOSE 8666/udp
EXPOSE 8666/tcp

## use s6-overlay
ADD https://github.com/just-containers/s6-overlay/releases/download/${S6_OVERLAY_VERSION}/s6-overlay-noarch.tar.xz /tmp
RUN tar -C / -Jxpf /tmp/s6-overlay-noarch.tar.xz
ADD https://github.com/just-containers/s6-overlay/releases/download/${S6_OVERLAY_VERSION}/s6-overlay-x86_64.tar.xz /tmp
RUN tar -C / -Jxpf /tmp/s6-overlay-x86_64.tar.xz
ENTRYPOINT /init
# CMD ["/etc/s6-overlay/s6-rc.d/svc-opentracker/run"] # IDK if this is correct
# USER 6969 # I think we can instead drop privs via s6