# SPDX-FileCopyrightText: 2022-2023 Sarah Vaupel <sarah.vaupel@uniworx.de>, Gregor Kleen <gregor@kleen.consulting>, Steffen Jost <jost@tcs.ifi.lmu.de>
#
# SPDX-License-Identifier: AGPL-3.0-or-later

{ self }: final: prev:

with prev.lib;

let
  created =
    let
      fromDate = builtins.readFile (prev.runCommand "date" { nativeBuildInputs = with final; [ coreutils ]; } ''
        printf '%s' $(date -Is -d '@${toString self.lastModified}') > $out
      '');
    in if self ? lastModified then fromDate else "1970-01-01T00:00:01Z";

  mkUniworxDocker = { isTest }: prev.dockerTools.buildImage {
    name = "uniworx${optionalString isTest "-test"}";
    tag =
      let
        versionFile = if isTest then ./test-version.json else ./version.json;
      in (builtins.fromJSON (prev.lib.readFile versionFile)).version;
    inherit created;

    contents = with final; [
      uniworx.uniworx.components.exes.uniworx
      prev.dockerTools.binSh findutils coreutils
      iana-etc
      # for PDF creation with Pandoc and LuaTeX
      #cups # needed for interface with print center -- did not work as intended, requires lpd running
      busybox # should provide a working lpr -- to be tested
      htop
      pdftk # for encrypting pdfs
      #texlive.combined.scheme-medium # too large for container in LMU build environment.
      (texlive.combine {
          inherit (texlive) scheme-basic
            babel-german babel-english booktabs textpos
            enumitem eurosym koma-script parskip xcolor dejavu
            # required fro LuaTeX
            luatexbase lualatex-math unicode-math selnolig
            ;
        })
      # just for manual testing within the pod, may be removef for production?
      curl wget netcat openldap
      unixtools.netstat htop gnugrep
      locale
    ];

    runAsRoot = ''
      #!${final.stdenv.shell}

      ${prev.dockerTools.shadowSetup}

      mkdir -p /var/lib

      groupadd -r uniworx
      useradd -r -g uniworx -d /var/lib/uniworx -M uniworx --uid 999
      install -d -g uniworx -o uniworx -m 0750 /var/lib/uniworx

      mkdir -p /var/log
      install -d -g uniworx -o uniworx -m 0755 /var/log/uniworx

      mkdir -p /usr/local/share/fonts
    '';
    # TODO copy font ttf files to /usr/local/share/fonts; they should then be accessible for LuaLaTeX

    config =
      let
        entrypoint = prev.writeScriptBin "uniworx-entrypoint" ''
          #!${final.zsh}/bin/zsh -xe

          cTime=$(date -Is)

          # export LOGDEST=/var/log/uniworx/''${cTime}.log # kubernetes prefers log via stdout
          typeset -a configs
          configs=()
          configDir=''${CONFIG_DIR-/cfg}
          if [[ -d "''${configDir}" ]]; then
            while IFS= read -d $'\0' cfg; do
              configs+=("''${(q)cfg}")
            done < <(find "''${configDir}" \( -name '*.yml' -o -name '*.yaml' \) -print0 | sort -rz)
          fi
          configs+=('${uniworxConfig}')
          cd /var/lib/uniworx
          exec -- uniworx ''${configs}
        '';
        postgresSchema = prev.writeText "schema.sql" ''
          CREATE USER uniworx WITH SUPERUSER;
          CREATE DATABASE uniworx;
          GRANT ALL ON DATABASE uniworx TO uniworx;
        '';

        postgresHba = prev.writeText "hba_file" ''
          local all all trust
        '';
        uniworxConfig = prev.writeText "uni2work.yml" ''
          port: 8080
          approot: "_env:APPROOT:http://localhost:8080"
        '';
      in {
        Cmd = [ "${entrypoint}/bin/uniworx-entrypoint" ];
        User = "uniworx:uniworx";
        ExposedPorts = {
          "8080/tcp" = {};
        };
        Volumes = {
          "/var/lib/uniworx" = {};
          "/var/log" = {};
        };
      };
  };
in
mapAttrs (_name: mkUniworxDocker) {
  uniworxTestDocker = { isTest = true; };
  uniworxDocker = { isTest = false; };
}
