name: Release Creation

on:
  release:
    types: [published]

jobs:
  build:
    runs-on: ubuntu-latest
    env:
      MODULE_ID: mgt2-compendium-amiral-denisov
      MANIFEST_FILE: module.json
      ARCHIVE_FILE: mgt2-compendium-amiral-denisov.zip
      RELEASE_TAG: ${{ github.event.release.tag_name }}
      REPOSITORY_URL: ${{ gitea.server_url }}/${{ gitea.repository }}
      RELEASE_BASE_URL: ${{ gitea.server_url }}/${{ gitea.repository }}/releases/download/${{ github.event.release.tag_name }}
      LATEST_BASE_URL: ${{ gitea.server_url }}/${{ gitea.repository }}/releases/download/latest

    steps:
      - name: Checkout repository
        uses: RouxAntoine/checkout@v3.5.4

      - name: Setup Node.js
        uses: https://github.com/actions/setup-node@v4
        with:
          node-version: "20"

      - name: Extract tag version number
        id: get_version
        uses: battila7/get-version-action@v2

      - name: Build release manifest
        run: |
          mkdir -p dist
          export RELEASE_VERSION="${{ steps.get_version.outputs.version-without-v }}"
          node <<'EOF'
          const fs = require('fs');
          const manifestPath = 'module.json';
          const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
          manifest.version = process.env.RELEASE_VERSION;
          manifest.url = process.env.REPOSITORY_URL;
          manifest.manifest = `${process.env.LATEST_BASE_URL}/${process.env.MANIFEST_FILE}`;
          manifest.download = `${process.env.RELEASE_BASE_URL}/${process.env.ARCHIVE_FILE}`;
          fs.writeFileSync(`dist/${process.env.MANIFEST_FILE}`, `${JSON.stringify(manifest, null, 2)}\n`);
          EOF

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

      - name: Create release archive
        run: |
          rm -rf package
          mkdir -p package
          cp dist/${MANIFEST_FILE} package/${MANIFEST_FILE}
          cp -R assets packs scripts styles templates package/
          (
            cd package
            zip -r "../${ARCHIVE_FILE}" .
          )

      - name: setup go
        uses: https://github.com/actions/setup-go@v4
        with:
          go-version: ">=1.20.1"

      - name: Use Go Action
        id: use-go-action
        uses: https://gitea.com/actions/release-action@main
        with:
          files: |-
            ./${{ env.ARCHIVE_FILE }}
            ./dist/${{ env.MANIFEST_FILE }}
          api_key: "${{secrets.ALLOW_PUSH_RELEASE}}"
