name: release

on:
  push:
    branches:
    tags:
      - 'v*'
  workflow_dispatch:
    inputs:
      refToBuild:
        description: 'Branch, tag or commit SHA1 to build'
        required: false
        type: string

jobs:
  release:
    permissions:
      contents: write
    strategy:
      matrix:
        # We can cross-compile from Linux to macOS and Windows. See .goreleaser.yaml
        # So running just on ubuntu is sufficient.
        go-version: [1.21.x]
        os: [ubuntu-latest]

    name: Release (${{ matrix.os}}, Go ${{ matrix.go-version }})
    runs-on: ${{ matrix.os }}
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
          ref: ${{ inputs.refToBuild }}
      - uses: actions/setup-go@v5
        with:
          go-version: ${{ matrix.go-version }}
          cache: true
      - shell: bash
        run: echo "sha_short=$(git rev-parse --short HEAD)" >> $GITHUB_ENV
      - id: cache
        uses: actions/cache@v3
        with:
          path: dist/${{ matrix.os }}
          key: ${{ matrix.go }}-${{ env.sha_short }}
      - name: Install Linux packages
        run: sudo apt-get update && sudo apt-get -y install libssl-dev cmake clang pkg-config
        if: runner.os == 'Linux'
      - name: Setup Rust
        uses: dtolnay/rust-toolchain@stable
      - name: Install bindgen-cli
        run: cargo install bindgen-cli
        if: runner.os == 'Linux'
      - name: Build KeyManager Rust library
        run: |
          cd keymanager
          cargo build --release
        if: runner.os == 'Linux'
      - name: Build all modules
        run: go build -v ./... ./cmd/... ./launcher/... ./verifier/...
      - name: Run GoReleaser
        uses: goreleaser/goreleaser-action@v6
        if: success() && (startsWith(github.ref, 'refs/tags/') || startsWith(inputs.refToBuild, 'refs/tags/')) && steps.cache.outputs.cache-hit != 'true'
        with:
          version: latest
          args: release --clean
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
