name: Publish Release to Digital Ocean

on:
  release:
    types: [published]
  workflow_dispatch:
    inputs:
      version:
        description: 'Tag to update'
        required: true


jobs:
  publish-to-digital-ocean:
    runs-on: ubuntu-latest

    steps:
      - name: Download Release Artifacts (Plugins)
        uses: dsaltares/fetch-gh-release-asset@master
        with:
          file: ".*"
          regex: true
          token: ${{ secrets.GITHUB_TOKEN }}
          target: "./"
          version: ${{ inputs.version && format('tags/{0}', inputs.version) || 'latest' }}

      - uses: cardinalby/git-get-release-action@v1
        id: release-info
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        with:
          latest: true
          prerelease: false
      - uses: actions/setup-node@v4
        with:
          node-version: '22.x'
      - run: npm install html-escaper@2 xml2js
      - name: Update Plugin Changelog
        uses: actions/github-script@v7
        with:
          script: |
            const fs = require('fs');
            const { escape } = require('html-escaper');
            const releaseNotes = escape(`${{ steps.release-info.outputs.body }}`);
            
            if (!releaseNotes) {
              console.error('No release notes found');
              process.exit(1);
            }

            // Read the plugin file
            const pluginPath = 'dynamix.unraid.net.plg';

            if (!fs.existsSync(pluginPath)) {
              console.error('Plugin file not found:', pluginPath);
              process.exit(1);
            }
            
            let pluginContent = fs.readFileSync(pluginPath, 'utf8');
            
            // Replace the changelog section using CDATA
            pluginContent = pluginContent.replace(
              /<CHANGES>[\s\S]*?<\/CHANGES>/,
              `<CHANGES>\n${releaseNotes}\n</CHANGES>`
            );
            
            // Validate the plugin file is valid XML
            const xml2js = require('xml2js');
            const parser = new xml2js.Parser({
              explicitCharkey: true,
              trim: true,
              explicitRoot: true,
              explicitArray: false,
              attrkey: 'ATTR',
              charkey: 'TEXT',
              xmlnskey: 'XMLNS',
              normalizeTags: false,
              normalize: false,
              strict: false // Try with less strict parsing
            });
            parser.parseStringPromise(pluginContent).then((result) => {
              if (!result) {
                console.error('Plugin file is not valid XML');
                process.exit(1);
              }
              console.log('Plugin file is valid XML');

              // Write back to file
              fs.writeFileSync(pluginPath, pluginContent);
            }).catch((err) => {
              console.error('Plugin file is not valid XML', err);
              process.exit(1);
            });

      - name: Upload Release Files to DO Spaces
        env:
          AWS_ACCESS_KEY_ID: ${{ secrets.DO_ACCESS_KEY }}
          AWS_SECRET_ACCESS_KEY: ${{ secrets.DO_SECRET_KEY }}
          AWS_DEFAULT_REGION: ${{ secrets.DO_SPACE_REGION }}
          AWS_ENDPOINT_URL: https://${{ secrets.DO_SPACE_REGION }}.digitaloceanspaces.com
        run: |
          # Upload files with explicit content encoding and public-read ACL
          aws s3 sync . s3://${{ secrets.DO_SPACE_NAME }}/unraid-api \
            --checksum-algorithm CRC32 \
            --no-guess-mime-type \
            --content-encoding none \
            --acl public-read

      - name: Upload Release Files to Cloudflare Bucket
        env:
          AWS_ACCESS_KEY_ID: ${{ secrets.CF_ACCESS_KEY_ID }}
          AWS_SECRET_ACCESS_KEY: ${{ secrets.CF_SECRET_ACCESS_KEY }}
          AWS_DEFAULT_REGION: auto
          AWS_ENDPOINT_URL: ${{ secrets.CF_ENDPOINT }}
        run: |
          # Upload files with explicit content encoding and public-read ACL
          aws s3 sync . s3://${{ secrets.CF_BUCKET }}/unraid-api \
            --checksum-algorithm CRC32 \
            --no-guess-mime-type \
            --content-encoding none \
            --acl public-read
