name: Release

on:
  push:
    tags:
      - "v*"
  workflow_dispatch:

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: false

env:
  BURROW_NIX_CACHE_URL: ${{ vars.BURROW_NIX_CACHE_URL || 'https://nix.burrow.net/burrow' }}
  BURROW_NIX_CACHE_PUBLIC_KEY: ${{ vars.BURROW_NIX_CACHE_PUBLIC_KEY }}

jobs:
  release:
    name: Release Build
    runs-on: namespace-profile-linux-medium
    steps:
      - name: Checkout
        uses: https://code.forgejo.org/actions/checkout@v4
        with:
          token: ${{ github.token }}
          fetch-depth: 0

      - name: Bootstrap Nix
        shell: bash
        run: |
          set -euo pipefail
          chmod +x Scripts/ci/ensure-nix.sh
          Scripts/ci/ensure-nix.sh

      - name: Build release artifacts
        shell: bash
        env:
          RELEASE_REF: ${{ github.ref_name }}
        run: |
          set -euo pipefail
          ref="${RELEASE_REF:-manual-${GITHUB_SHA::7}}"
          export RELEASE_REF="${ref}"
          chmod +x Scripts/ci/build-release-artifacts.sh
          nix develop .#ci -c Scripts/ci/build-release-artifacts.sh

      - name: Flatten release assets
        shell: bash
        env:
          RELEASE_REF: ${{ github.ref_name }}
        run: |
          set -euo pipefail
          ref="${RELEASE_REF:-manual-${GITHUB_SHA::7}}"
          mkdir -p dist/release-assets
          find "dist/builds/${ref}" -type f \( -name '*.tar.gz' -o -name '*.zip' -o -name '*.sha256' -o -name 'README.txt' \) -exec cp {} dist/release-assets/ \;
          rm -rf dist/builds
          cp dist/release-assets/* dist/
          find dist -maxdepth 1 -type f -print | sort

      - name: Upload release artifacts
        uses: https://code.forgejo.org/actions/upload-artifact@v4
        with:
          name: burrow-release-${{ github.ref_name }}
          path: dist/*
          if-no-files-found: error

      - name: Publish Forgejo release
        if: startsWith(github.ref, 'refs/tags/')
        shell: bash
        env:
          RELEASE_TAG: ${{ github.ref_name }}
          API_URL: ${{ github.api_url }}
          REPOSITORY: ${{ github.repository }}
          TOKEN: ${{ github.token }}
        run: |
          set -euo pipefail
          chmod +x Scripts/ci/publish-forgejo-release.sh
          nix develop .#ci -c Scripts/ci/publish-forgejo-release.sh
