local copy_script(name) = {
  name: 'podman | Install ' + name + ' wrapper script',
  template: {
    src: name + '.j2',
    dest: '{{ xdg_dir.bin_home }}/' + name,
    mode: '755',
  },
};

local podman(name) = std.prune(
  {
    local normalized_name = std.strReplace(name, '-', '_'),
    local version_variable = '{{ ' + normalized_name + '_version }}',

    name: 'podman | Create ' + name + ' shim',
    tags: name,
    block: [
      {
        name: 'podman | Build ' + name + ' container image',
        'containers.podman.podman_image': {
          name: name,
          build: { extra_args: '--build-arg ' + std.asciiUpper(normalized_name) + '_VERSION=' + version_variable },
          path: '{{ role_path }}/build_dirs/' + name,
          tag: version_variable,
          state: 'present',
        },
      },
      copy_script(name),
    ],
  }
);

// Ref: https://gitlab.alpinelinux.org/alpine/docker-abuild
local aports_dev =
  local name = 'aports-dev';
  local normalized_name = std.strReplace(name, '-', '_');
  local abuild_dir = '{{ ansible_user_dir }}/.abuild';

  // NOTE: keep this in sync with what is defined in the Dockerfile.
  // GID and UID are the same when the group is added via `adduser`
  local builder_uid = '1069';

  local podman_args = [
    '--rm',
    '--tty',
    '--interactive',
    '--gidmap',
    builder_uid + ':0:1',
    '--gidmap',
    '0:1:' + builder_uid,
    '--uidmap',
    builder_uid + ':0:1',
    '--uidmap',
    '0:1:' + builder_uid,
    '--volume',
    'abuild-distfiles:/var/cache/distfiles',
    '--volume',
    'abuild-apkcache:/var/cache/apk',
    '--volume',
    'abuild-ccache:/home/builder/.ccache',
    '--volume',
    '{{ ansible_user_dir }}/.abuild:/home/builder/.abuild',
    '--volume',
    '{{ ansible_user_dir }}/packages:/home/builder/packages',
    '--volume',
    '{{ ansible_user_dir }}/Code/gitlab.alpinelinux.org/folliehiyuki/aports:/home/builder/aports',
  ];

  [
    x { tags: name }
    for x in [
      {
        name: 'podman | Get current date as ' + name + "'s image tag",
        command: '/bin/date -u "+%Y-%m-%d"',
        changed_when: false,
        register: normalized_name + '_version',
      },
      {
        name: 'podman | Build ' + name + ' container image',
        'containers.podman.podman_image': {
          name: name,
          path: '{{ role_path }}/build_dirs/' + name,
          tag: '{{ ' + normalized_name + '_version.stdout }}',
          state: 'present',
        },
        register: normalized_name + '_image',
      },
      {
        name: 'podman | Create necessary bind-mount directories for aports-dev container',
        file: {
          path: '{{ item }}',
          state: 'directory',
          mode: '755',
        },
        loop: [abuild_dir, '{{ ansible_user_dir }}/packages'],
      },
      {
        name: 'podman | Check whether abuild-keygen has been run before',
        find: {
          paths: [abuild_dir],
          file_type: 'file',
          recurse: false,
          patterns: ['*.rsa'],
        },
        register: 'abuild_key_found',
      },
      {
        name: 'podman | Run abuild-keygen',
        'containers.podman.podman_container': {
          name: 'abuild-keygen',
          image: '{{ ' + normalized_name + '_image.image[0].RepoDigests[0] }}',
          entrypoint: '',
          rm: true,
          command: ['/usr/bin/abuild-keygen', '-a', '-n'],
          user: builder_uid,
          // FIXME: this needs manual quoting in the pretty-generated YAML file.
          // Why? Because PyYAML (used by Ansible, obviously) does not support YAML 1.2 spec (yet),
          // which removed the stupid `Sexagesimal number` thing. It still exists in 1.1 spec.
          // Ref: https://ruudvanasseldonk.com/2023/01/11/the-yaml-document-from-hell#sexagesimal-numbers
          // NOTE: it probably will be fine (maybe) when either PR #555 or #700 on https://github.com/yaml/pyyaml is merged.
          // => Use raw output from Jsonnet instead of piping to yq (for pretty-printing) for now.
          gidmap: [
            builder_uid + ':0:1',
            '0:1:' + builder_uid,
          ],
          uidmap: [
            builder_uid + ':0:1',
            '0:1:' + builder_uid,
          ],
          volume: [
            abuild_dir + ':/home/builder/.abuild',
            '{{ xdg_dir.config_home }}/git/config:/home/builder/.gitconfig',
          ],
        },
        when: 'abuild_key_found.matched == 0',
      },
    ]
  ] + [
    copy_script(x) {
      tags: name,
      vars: {
        podman_args: std.join(' ', podman_args),
        container_image_repo: '{{ ' + normalized_name + '_image.image[0].RepoDigests[0] }}',
      },
    }
    for x in [name, 'abuild']
  ];

local vagrant =
  local name = 'vagrant';
  [
    x {
      tags: name,
      vars: {
        vagrant_image_repository: 'docker.io/vagrantlibvirt/vagrant-libvirt',
        vagrant_image_tag: 'latest-slim',
      },
    }
    for x in [
      {
        name: 'podman | Keep vagrant container image up-to-date',
        'containers.podman.podman_image': {
          name: '{{ vagrant_image_repository }}',
          tag: '{{ vagrant_image_tag }}',
          force: true,
        },
      },
      copy_script(name),
    ]
  ];

local kcli =
  local name = 'kcli';
  [
    x { tags: name }
    for x in [
      {
        name: 'podman | Create ' + name + ' shim',
        template: {
          src: name + '.j2',
          dest: '{{ xdg_dir.bin_home }}/' + name,
          mode: '755',
        },
      },
      {
        name: 'podman | Symlink kweb script to ' + name,
        file: {
          src: './' + name,
          dest: '{{ xdg_dir.bin_home }}/kweb',
          state: 'link',
        },
      },
    ]
  ];

std.manifestYamlDoc(
  [podman(x) for x in ['ltex-ls', 'translate-shell', 'marksman']]
  + aports_dev + vagrant + kcli,
  quote_keys=false
)
