name: Build and Release Module and Documentation

on:
  push:
    tags: [ "v*" ]
    paths-ignore:
    - "docs/**"

env:
  REGISTRY: ghcr.io
  IMAGE_NAME: ${{ github.repository }}

jobs:

      
  build:
    runs-on: ubuntu-latest

    permissions:
      contents: write
      packages: write
      attestations: write
      id-token: write


    steps:
    - uses: actions/checkout@v4
    - uses: pnpm/action-setup@v4
    - uses: actions/setup-node@v4
      with:
        node-version: 22.x
        cache: "pnpm"

    - name: Dump
      env:
        GHC: ${{ toJson(github) }}
      run: 'echo "Dump: ${GHC}"'

    - name: Extract version from tag without the v
      id: get-version
      run: echo "v=${GITHUB_REF_NAME#v}" >> "$GITHUB_OUTPUT"

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

    - name: Test
      run: pnpm test

    - name: Compile build
      run: pnpm build

    # Substitute the Manifest and Download URLs in the `module.json`.
    - name: Substitute Manifest and Download Links For Versioned Ones
      id: sub_manifest_link_version
      uses: microsoft/variable-substitution@v1
      with:
        files: 'module.json'
      env:
        version: ${{steps.get-version.outputs.v}}
        url: https://github.com/${{github.repository}}
        readme: https://github.com/${{github.repository}}/blob/master/README.md
        bugs: https://github.com/${{github.repository}}/issues
        changelog: https://github.com/${{github.repository}}/releases/latest
        manifest: https://github.com/${{github.repository}}/releases/latest/download/module.json
        download: https://github.com/${{github.repository}}/releases/download/${{github.ref_name}}/module.zip

    # Create a zip file with all files required by the module to add to the release.
    - name: Bundle into ZIP file
      run: zip -r ./module.zip module.json assets/ dist/ lang/ packs/ LICENSE documentation-${{ github.ref_name }}.zip

    - name: Recover Release Data
      uses: dawidd6/action-download-artifact@v6
      with:
        workflow: bump-version.yml
        workflow_conclusion: success
        name: release-${{ github.ref_name }}
        path: ${{ github.workspace }}/release-${{ github.ref_name }}
        search_artifacts: true


    - name: Release
      if: ${{ !env.ACT }}
      uses: softprops/action-gh-release@v1
      with:
        body_path: "${{ github.workspace }}/release-${{ github.ref_name }}/release-note.md"
        tag_name: ${{ github.ref_name }}
        files: |
            module.json
            module.zip
      env:
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
