ARG BASE="20-jammy-full"
FROM ghcr.io/koush/scrypted-common:${BASE}

# avahi advertiser support
RUN apt-get update && apt-get -y install \
    libnss-mdns \
    avahi-discover \
    libavahi-compat-libdnssd-dev \
    xz-utils

# copy configurations and scripts
COPY fs /

# s6 process supervisor
ARG S6_OVERLAY_VERSION=3.1.5.0
ENV S6_CMD_WAIT_FOR_SERVICES_MAXTIME=0
ENV S6_KEEP_ENV=1
ARG TARGETARCH
RUN case "${TARGETARCH}" in \
    amd64) S6_ARCH='x86_64';; \
    arm) S6_ARCH='armhf';; \
    arm64) S6_ARCH='aarch64';; \
    *) echo "Your system architecture isn't supported."; exit 1 ;; \
    esac \
  && cd /tmp \
  && set -x \
  && curl -SLOf https://github.com/just-containers/s6-overlay/releases/download/v${S6_OVERLAY_VERSION}/s6-overlay-noarch.tar.xz \
  && tar -C / -Jxpf /tmp/s6-overlay-noarch.tar.xz \
  && curl -SLOf  https://github.com/just-containers/s6-overlay/releases/download/v${S6_OVERLAY_VERSION}/s6-overlay-${S6_ARCH}.tar.xz \
  && tar -C / -Jxpf /tmp/s6-overlay-${S6_ARCH}.tar.xz

ENTRYPOINT ["/init"]

WORKDIR /
# cache bust
ADD "https://www.random.org/cgi-bin/randbyte?nbytes=10&format=h" skipcache
ARG SCRYPTED_INSTALL_VERSION="latest"
RUN test -n "$SCRYPTED_INSTALL_VERSION"
RUN npx -y scrypted@latest install-server ${SCRYPTED_INSTALL_VERSION}
WORKDIR /server

# this prevents node from preferring ipv6 addresses locally on
# networks with busted ipv6 setups.
# https://github.com/nodejs/node/issues/41145#issuecomment-992948130
ENV NODE_OPTIONS="--dns-result-order=ipv4first"

# changing this forces pip and npm to perform reinstalls.
# if this base image changes, this version must be updated.
ENV SCRYPTED_BASE_VERSION="20240321"

CMD npm --prefix /server exec scrypted-serve
