FROM sapmachine:21-jre-headless-ubuntu


ENV WORKDIR_PATH=/workspace
ENV CONFIG_PATH=${WORKDIR_PATH}/config
ENV DATA_PATH=${WORKDIR_PATH}/data

ADD ./src ${CONFIG_PATH}
RUN  mkdir ${DATA_PATH}


RUN mkdir ${DATA_PATH}/logs && \
    ln -sf ${DATA_PATH}/logs ${CONFIG_PATH}

VOLUME ${DATA_PATH}


ENV MEMORY=4G
ENV PROXY_SECRET=change_me
ENV SERVERS=lobby="lobby:25565";survival="survival:25565"
ENV TRY=lobby;survival
ENV LIBRELOGIN_LIMBOS=limbo
ENV LIBRELOGIN_LOBBIES=lobby

WORKDIR ${WORKDIR_PATH}/config

EXPOSE 25565/tcp

# TODO: Make awk commands sapn multiple lines
# TODO: Use one call to awk to perform substitutions
CMD \
    # Add proxy secret
    sed -i "s/_PROXY_SECRET_/${PROXY_SECRET}/g" forwarding.secret && \
    # Add servers to velocity.toml
    awk -v servers_str="${SERVERS}" '{ count=split(servers_str,servers_arr,";"); servers_fmt_str = ""; for (i = 1; i <= count; i++) servers_fmt_str = servers_fmt_str servers_arr[i] "\n"; sub(/_SERVERS_/,servers_fmt_str); print }' velocity.toml > velocity.toml.tmp && mv -T -f velocity.toml.tmp velocity.toml && \
    # Add try servers to velocity.toml
    awk -v try_str="${TRY}" '{ count=split(try_str,try_arr,";"); try_fmt_str = ""; for (i = 1; i <= count; i++) try_fmt_str = try_fmt_str "\"" try_arr[i] "\"" ",\n    "; sub(/_TRY_/,try_fmt_str); print }' velocity.toml > velocity.toml.tmp && mv -T -f velocity.toml.tmp velocity.toml && \
    # Add limbo servers to librelogin config
    awk -v limbos_str="${LIBRELOGIN_LIMBOS}" '{ count=split(limbos_str,limbos_arr,";"); limbos_fmt_str = ""; for (i = 1; i <= count; i++) limbos_fmt_str = limbos_fmt_str limbos_arr[i] ",\n    "; sub(/_LIBRELOGIN_LIMBOS_/,limbos_fmt_str); print }' plugins/librelogin/config.conf > plugins/librelogin/config.conf.tmp && mv -T -f plugins/librelogin/config.conf.tmp plugins/librelogin/config.conf && \
    # Add lobby servers to librelogin config
    awk -v lobbies_str="${LIBRELOGIN_LOBBIES}" '{ count=split(lobbies_str,lobbies_arr,";"); lobbies_fmt_str = ""; for (i = 1; i <= count; i++) lobbies_fmt_str = lobbies_fmt_str lobbies_arr[i] ",\n        "; sub(/_LIBRELOGIN_LOBBIES_/,lobbies_fmt_str); print }' plugins/librelogin/config.conf > plugins/librelogin/config.conf.tmp && mv -T -f plugins/librelogin/config.conf.tmp plugins/librelogin/config.conf && \
    java -Xms${MEMORY} -Xmx${MEMORY} -XX:+UseG1GC -XX:G1HeapRegionSize=4M -XX:+UnlockExperimentalVMOptions -XX:+ParallelRefProcEnabled -XX:+AlwaysPreTouch -XX:MaxInlineLevel=15 -jar *.jar
