local archs = [
  { target: 'aarch64-unknown-linux-gnu', short: 'arm64-gnu' },
  { target: 'aarch64-unknown-linux-musl', short: 'arm64-musl' },
  { target: 'x86_64-pc-windows-gnu', short: 'windows-amd64' },
  { target: 'x86_64-unknown-linux-gnu', short: 'amd64-gnu' },
  { target: 'x86_64-unknown-linux-musl', short: 'amd64-musl' },
];

local getStepName(arch) = 'Build for ' + arch.short;

local getExeName(arch) = if std.startsWith(arch.short, 'windows') then '.exe' else '';

local add_build_steps() = [
  {
    name: getStepName(arch),
    image: 'img.kie.rs/jjkiers/rust-dind-cross:1.62-slim',
    volumes: [
      {
        name: 'dockersock',
        path: '/var/run',
      },
      {
        name: 'rustup',
        path: '/usr/local/rustup',
      },
    ],
    commands: [
      'echo Hello World from Jsonnet on ' + arch.target + '!',
      'cross build --release --target ' + arch.target,
      'cp target/' + arch.target + '/release/drone-test' + getExeName(arch) + ' artifacts/drone-test-' + arch.short + getExeName(arch),
      'rm -rf target/' + arch.target + '/release/*',
    ],
    environment: {
      CROSS_REMOTE: true,
    },
    depends_on: ['Wait for Docker'],
  }
  for arch in archs
];

{
  kind: 'pipeline',
  type: 'docker',
  name: 'default',
  platform: {
    arch: 'amd64',
  },
  steps:
    [{
      name: 'Wait for Docker',
      image: 'img.kie.rs/jjkiers/rust-dind-cross:1.62-slim',
      commands: [
        'while ! docker image ls; do sleep 1; done',
        'docker info',
        'docker pull hello-world:latest',
        'mkdir artifacts',
      ],
      volumes: [{
        name: 'dockersock',
        path: '/var/run',
      }],
    }] +
    add_build_steps() +
    [
      {
        name: 'Show built artifacts',
        image: 'img.kie.rs/jjkiers/rust-dind-cross:1.62-slim',
        commands: [
          'ls -lah artifacts',
        ],
        depends_on: [getStepName(a) for a in archs],
      },
      {
        name: 'Create release on gitea',
        image: 'plugins/gitea-release',
        settings: {
          api_key: {
            from_secret: 'gitea_token',
          },
          base_url: 'https://code.kiers.eu',
          files: 'artifacts/*',
          checksum: 'sha256',
        },
        when: {
          event: ['tag', 'promote'],
        },
        depends_on: ['Show built artifacts'],
      },
    ],

  services: [{
    name: 'docker',
    image: 'docker:dind',
    privileged: true,
    volumes: [
      {
        name: 'dockersock',
        path: '/var/run',
      },
      {
        name: 'docker-storage',
        path: '/var/lib/docker',
      },
    ],
  }],

  volumes: [
    {
      name: 'dockersock',
      temp: {},
    },
    {
      name: 'docker-storage',
      host: {
        path: '/srv/drone/docker-dind-rust',
      },
    },
    {
      name: 'rustup',
      host: {
        path: '/srv/drone/rustup',
      },
    },
  ],

  image_pull_secrets: ['docker_private_repo'],
}