name: "deliver-github-asset"
description: "Deliver asset to github release"
inputs:
  file_pattern:
    description: "The path to the file to upload"
    required: true
  github_release:
    description: "The github release name"
    required: true
  token_download_centreon_com:
    description: "The token to call download.centreon.com api"
    required: false

runs:
  using: "composite"
  steps:
    - name: Deliver asset to github release
      uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v7.0.1
      env:
        FILE_PATTERN: ${{ inputs.file_pattern }}
        GITHUB_RELEASE: ${{ inputs.github_release }}
        TOKEN_DOWNLOAD_CENTREON_COM: ${{ inputs.token_download_centreon_com }}
      with:
        script: |
          const path = require('path');
          const fs = require('fs');

          const githubRelease = process.env.GITHUB_RELEASE;
          const filePattern = process.env.FILE_PATTERN;

          const delay = ms => new Promise(res => setTimeout(res, ms));

          let releaseId = null;

          for (let i = 0; i < 10; i++) {
            const { data: releases } = await github.rest.repos.listReleases({
              ...context.repo,
              per_page: 100,
              page: 1,
            });

            for (const release of releases) {
              if (release.tag_name === githubRelease) {
                releaseId = release.id;
                break;
              }
            }

            if (releaseId !== null) {
              break;
            }

            console.log(`Release ${githubRelease} not found, retrying...`);

            await delay(30000);
          }

          if (releaseId === null) {
            core.warning(`Release ${githubRelease} does not exist`);
            return;
          }

          const globber = await glob.create(filePattern);
          for await (const file of globber.globGenerator()) {
            const fileName = path.basename(file);

            core.info(`Uploading asset ${fileName} to release ${githubRelease}`);

            github.rest.repos.uploadReleaseAsset({
              ...context.repo,
              release_id: releaseId,
              name: fileName,
              data: fs.readFileSync(file),
            });

            core.info(`Asset ${fileName} uploaded to release ${githubRelease}`);

            if (process.env.TOKEN_DOWNLOAD_CENTREON_COM) {
              const matches = fileName.match(/^([\w-]+)(?:-|_)(\d+\.\d+)\.(\d+).*\.(\w+)$/);
              if (matches) {
                const product = matches[1];
                const majorVersion = matches[2];
                const minorVersion = matches[3];
                const extension = matches[4];

                console.log("Product:", product);
                console.log("Major Version:", majorVersion);
                console.log("Minor Version:", minorVersion);
                console.log("Extension:", extension);

                const fileHash = require('crypto').createHash('md5').update(fs.readFileSync(file)).digest('hex');
                const fileSize = fs.statSync(file).size;

                let distribSuffix = '';
                const distribMatches = fileName.match(/(el|deb|ubuntu|exe)\.?(\d+(?:\.\d+)?)?/);
                if (distribMatches) {
                  switch (distribMatches[1]) {
                    case 'el':
                      distribSuffix = `-${distribMatches[1]}${distribMatches[2]}`;
                      break;
                    case 'deb':
                      distribSuffix = `-debian-${distribMatches[2]}`;
                      break;
                    case 'ubuntu':
                      distribSuffix = `-${distribMatches[1]}-${distribMatches[2]}`;
                      break;
                    case 'exe':
                      distribSuffix = '-windows';
                      break;
                  }
                }

                let archSuffix = '';
                if (fileName.includes('amd64') || fileName.includes('x86_64')) {
                  archSuffix = '-amd64';
                } else if (fileName.includes('arm64') || fileName.includes('aarch64')) {
                  archSuffix = '-arm64';
                }

                const downloadUrl = new URL('https://download.centreon.com/api/');
                const downloadParams = {
                  token: process.env.TOKEN_DOWNLOAD_CENTREON_COM,
                  product: product,
                  release: majorVersion,
                  version: `${majorVersion}.${minorVersion}${distribSuffix}${archSuffix}`,
                  extension: extension,
                  md5: fileHash,
                  size: fileSize,
                  ddos: 0,
                  dryrun: 0,
                  release_url: `https://github.com/centreon/centreon-collect/releases/download/${githubRelease}/${fileName}`,
                };
                downloadUrl.search = new URLSearchParams(downloadParams).toString();

                core.info(`Publishing asset ${fileName} to download.centreon.com`);

                console.log(await fetch(downloadUrl));

                core.info(`Asset ${fileName} published on download.centreon.com`);
              } else {
                core.warning(`Asset ${fileName} cannot be parsed to extract product and version information, skipping download.centreon.com upload`);
              }
            }
          }
