name: Release nightly

on:
  schedule:
    - cron: "0 0 * * *" # every day at midnight
  workflow_dispatch:

concurrency:
  group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
  cancel-in-progress: true

jobs:
  check-latest-run:
    runs-on: "ubuntu-latest"
    steps:
      - uses: octokit/request-action@v2.x
        id: check_last_run
        with:
          route: GET /repos/${{github.repository}}/actions/workflows/release-nightly.yml/runs?per_page=1&status=completed
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
    outputs:
      last_sha: ${{ fromJson(steps.check_last_run.outputs.data).workflow_runs[0].head_sha }}

  release-nightly:
    if: needs.check-latest-run.outputs.last_sha != github.sha
    runs-on: ubuntu-latest
    needs: [check-latest-run]
    env:
      working-directory: go/src/github.com/ignite/cli

    steps:
      - uses: actions/checkout@v4

      - name: Delete the nightly release
        uses: dev-drprasad/delete-tag-and-release@v1.1
        with:
          tag_name: nightly
          delete_release: true
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Push new nightly tag
        uses: mathieudutour/github-tag-action@v6.2
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          custom_tag: nightly
          tag_prefix: ""

      - name: Create the new nightly release
        uses: ncipollo/release-action@v1
        with:
          tag: nightly
          name: nightly
          body: "Install and move the CLI to your bin directory: `curl https://get.ignite.com/cli@nightly! | bash`"
          prerelease: true

  releases-binaries:
    if: needs.check-latest-run.outputs.last_sha != github.sha
    name: Release Go Binary
    needs: [check-latest-run]
    runs-on: ubuntu-latest
    strategy:
      matrix:
        goos: [linux, darwin]
        goarch: [amd64, arm64]
    steps:
      - uses: actions/checkout@v4
      - uses: wangyoucao577/go-release-action@v1.53
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          project_path: "./ignite/cmd/ignite"
          binary_name: "ignite"
          asset_name: ignite-nightly-${{ matrix.goos }}-${{ matrix.goarch }}
          release_name: "nightly"
          goos: ${{ matrix.goos }}
          goarch: ${{ matrix.goarch }}
          ldflags: -s -w -X github.com/ignite/cli/v29/ignite/version.Version=nightly
          retry: 10
