name: Release

permissions:
  id-token: write
  contents: write

on:
  push:
    tags:
      - 'v*'

jobs:
  release:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
      - uses: pnpm/action-setup@v4
        with:
          version: 9
      - uses: actions/setup-node@v4
        with:
          node-version: lts/*
          registry-url: https://registry.npmjs.org/

      - run: pnpm dlx changelogithub
        env:
          GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}}

  build-binaries:
    needs: release
    runs-on: ubuntu-latest
    strategy:
      fail-fast: false
      matrix:
        include:
          - goos: linux
            goarch: amd64
          - goos: linux
            goarch: arm64
          - goos: darwin
            goarch: amd64
          - goos: darwin
            goarch: arm64
          - goos: windows
            goarch: amd64
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - uses: pnpm/action-setup@v4
        with:
          version: 10

      - uses: actions/setup-node@v4
        with:
          node-version: lts/*

      - uses: oven-sh/setup-bun@v2

      - uses: actions/setup-go@v5
        with:
          go-version-file: go.mod

      - name: Install UPX
        run: sudo apt-get update && sudo apt-get install -y upx-ucl

      - name: Install JS dependencies
        run: pnpm install --frozen-lockfile

      - name: Build release binary
        env:
          TARGET_OS: ${{ matrix.goos }}
          TARGET_ARCH: ${{ matrix.goarch }}
          VERSION: ${{ github.ref_name }}
          COMMIT_HASH: ${{ github.sha }}
          OUTPUT_DIR: dist
          UPX_COMPRESS_AGENT_BIN: "true"
          AUTO_INSTALL_UPX: "true"
          UPX_ARGS: "-3"
        run: scripts/release.sh

      - name: Upload release assets
        uses: softprops/action-gh-release@v2
        with:
          files: |
            dist/*.tar.gz
            dist/*.zip
          tag_name: ${{ github.ref_name }}
          overwrite_files: true
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      # # Uncomment the following lines to publish to npm on CI
      #
      # - run: pnpm install
      # - run: pnpm publish -r --access public
      #   env:
      #     NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}}
      #     NPM_CONFIG_PROVENANCE: true
