name: Build cigocacher

on:
  # Released on-demand. The commit will be used as part of the tag, so generally
  # prefer to release from main where the commit is stable in linear history.
  workflow_dispatch:

jobs:
  build:
    strategy:
      matrix:
        GOOS: ["linux", "darwin", "windows"]
        GOARCH: ["amd64", "arm64"]
    runs-on: ubuntu-24.04
    env:
      GOOS: "${{ matrix.GOOS }}"
      GOARCH: "${{ matrix.GOARCH }}"
      CGO_ENABLED: "0"
    steps:
    - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
    - name: Build
      run: |
        OUT="cigocacher$(./tool/go env GOEXE)"
        ./tool/go build -o "${OUT}" ./cmd/cigocacher/
        tar -zcf cigocacher-${{ matrix.GOOS }}-${{ matrix.GOARCH }}.tar.gz "${OUT}"

    - uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
      with:
        name: cigocacher-${{ matrix.GOOS }}-${{ matrix.GOARCH }}
        path: cigocacher-${{ matrix.GOOS }}-${{ matrix.GOARCH }}.tar.gz

  release:
    runs-on: ubuntu-24.04
    needs: build
    permissions:
      contents: write
    steps:
      - name: Download all artifacts
        uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
        with:
          pattern: 'cigocacher-*'
          merge-multiple: true
      # This step is a simplified version of actions/create-release and
      # actions/upload-release-asset, which are archived and unmaintained.
      - name: Create release
        uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
        with:
          script: |
            const fs = require('fs');
            const path = require('path');

            const { data: release } = await github.rest.repos.createRelease({
              owner: context.repo.owner,
              repo: context.repo.repo,
              tag_name: `cmd/cigocacher/${{ github.sha }}`,
              name: `cigocacher-${{ github.sha }}`,
              draft: false,
              prerelease: true,
              target_commitish: `${{ github.sha }}`
            });

            const files = fs.readdirSync('.').filter(f => f.endsWith('.tar.gz'));
            
            for (const file of files) {
              await github.rest.repos.uploadReleaseAsset({
                owner: context.repo.owner,
                repo: context.repo.repo,
                release_id: release.id,
                name: file,
                data: fs.readFileSync(file)
              });
              console.log(`Uploaded ${file}`);
            }
