name: release

on:
  push:
    tags:
      - 'v*'
  workflow_dispatch:
    inputs:
      tag:
        description: 'Release tag (e.g. v1.2.3). If empty, uses current ref name.'
        required: false
        type: string

permissions:
  contents: write

jobs:
  build-and-package:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Setup Go
        uses: actions/setup-go@v5
        with:
          go-version-file: go.mod
          cache: true

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: 'npm'
          cache-dependency-path: webui/package-lock.json

      - name: Install packaging tools
        run: |
          sudo apt-get update
          sudo apt-get install -y zip

      - name: Resolve build version
        id: ver
        run: |
          if [ "${{ github.event_name }}" = "workflow_dispatch" ] && [ -n "${{ inputs.tag }}" ]; then
            raw="${{ inputs.tag }}"
          elif [[ "${GITHUB_REF}" == refs/tags/* ]]; then
            raw="${GITHUB_REF_NAME}"
          else
            raw="$(git describe --tags --always --dirty 2>/dev/null || echo dev)"
          fi
          version="${raw#v}"
          echo "raw=$raw" >> "$GITHUB_OUTPUT"
          echo "version=$version" >> "$GITHUB_OUTPUT"
          echo "Build version: $version (from $raw)"

      - name: Build and package release artifacts
        run: |
          set -euo pipefail
          make clean
          make package-all VERSION="${{ steps.ver.outputs.version }}"

      - name: Upload artifacts
        uses: actions/upload-artifact@v4
        with:
          name: release-artifacts
          path: |
            build/*.tar.gz
            build/*.zip
            build/checksums.txt
          if-no-files-found: error

  publish-release:
    needs: build-and-package
    runs-on: ubuntu-latest
    if: startsWith(github.ref, 'refs/tags/') || github.event_name == 'workflow_dispatch'
    steps:
      - name: Download artifacts
        uses: actions/download-artifact@v4
        with:
          name: release-artifacts
          path: build

      - name: Resolve tag
        id: tag
        run: |
          if [ "${{ github.event_name }}" = "workflow_dispatch" ] && [ -n "${{ inputs.tag }}" ]; then
            echo "name=${{ inputs.tag }}" >> "$GITHUB_OUTPUT"
          else
            echo "name=${GITHUB_REF_NAME}" >> "$GITHUB_OUTPUT"
          fi

      - name: Create GitHub Release
        uses: softprops/action-gh-release@v2
        with:
          tag_name: ${{ steps.tag.outputs.name }}
          name: ${{ steps.tag.outputs.name }}
          generate_release_notes: true
          files: |
            build/*.tar.gz
            build/*.zip
            build/checksums.txt
