name: Release Creation

on:
  release:
    types: [published]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
    - run: echo "💡 The ${{ gitea.repository }} repository will be cloned to the runner."

    - uses: RouxAntoine/checkout@v3.5.4

    # get part of the tag after the `v`
    - name: Extract tag version number
      id: get_version
      uses: battila7/get-version-action@v2

    # 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.version-without-v}}
        url: https://www.uberwald.me/gitea/${{gitea.repository}}
        manifest: https://www.uberwald.me/gitea/public/${{gitea.repository}}/releases/download/latest/module.json
        download: https://www.uberwald.me/gitea/${{gitea.repository}}/releases/download/${{gitea.event.release.tag_name}}/module.zip

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

    - name: Install dependencies
      run: npm ci

    - name: Build
      run: npm run build

    # Create a zip file with all files required by the module to add to the release
    - run: |
         apt update -y
         apt install -y zip

    - run: node scripts/package.mjs

    - name: Upload release assets
      run: |
        # Upload module.zip
        curl -s -X POST \
          -H "Content-Type: application/octet-stream" \
          -H "Authorization: token ${{secrets.ALLOW_PUSH_RELEASE}}" \
          --data-binary @./module.zip \
          "https://www.uberwald.me/api/v1/repos/${{gitea.repository}}/releases/${{gitea.event.release.id}}/assets?name=module.zip"
        
        # Upload module.json
        curl -s -X POST \
          -H "Content-Type: application/json" \
          -H "Authorization: token ${{secrets.ALLOW_PUSH_RELEASE}}" \
          --data-binary @./module.json \
          "https://www.uberwald.me/api/v1/repos/${{gitea.repository}}/releases/${{gitea.event.release.id}}/assets?name=module.json"

    - name: Publish to Foundry server
      uses: https://github.com/djlechuck/foundryvtt-publish-package-action@v1
      with:
        token: ${{ secrets.FOUNDRYVTT_RELEASE_TOKEN }}
        id: 'scrying-pool'
        version: ${{gitea.event.release.tag_name}}
        manifest: 'https://www.uberwald.me/gitea/public/${{gitea.repository}}/releases/download/latest/module.json'
        notes: 'https://www.uberwald.me/gitea/${{gitea.repository}}/releases/download/${{gitea.event.release.tag_name}}/module.zip'
        compatibility-minimum: '14'
        compatibility-verified: '14'
