name: Download Release Asset

on:
  workflow_dispatch: 
  release:
    types:
      - published

jobs:
  download-release-asset:
    runs-on: ubuntu-latest

    steps:
      # Fetch the latest release and its assets
      - name: Fetch Latest Release
        id: fetch-release
        uses: actions/github-script@v6
        with:
          script: |
            const release = await github.rest.repos.getLatestRelease({
              owner: context.repo.owner,
              repo: context.repo.repo,
            });
            if (!release.data.assets.length) {
              throw new Error("No assets found in the latest release.");
            }
            // Get the first asset
            const asset = release.data.assets[0]; 
            console.log("Release Name:", release.data.name);
            console.log("Asset Name:", asset.name);
            console.log("Asset URL:", asset.url);
            // Set outputs for asset URL and name
            core.setOutput("asset_url", asset.url);
            core.setOutput("asset_name", asset.name);

      # Create a new directory for downloading
      - name: Create Download Directory
        run: mkdir -p download_dir

      # Download the asset to the new directory
      - name: Download Asset
        run: |
          curl -L \
            -H "Authorization: token ${{ secrets.MDA_PORTAL_CUSTOM_GITHUB_TOKEN }}" \
            -H "Accept: application/octet-stream" \
            "${{ steps.fetch-release.outputs.asset_url }}" \
            --output "download_dir/${{ steps.fetch-release.outputs.asset_name }}"
            
      # Verify the contents of the directory
      - name: List Files in Download Directory
        run: |
          ls -l download_dir
          echo "this is file type: "
          file download_dir/${{ steps.fetch-release.outputs.asset_name }}

      # Upload the asset to ServiceNow 
      - name: Upload zip to ServiceNow
        run: |
           curl -v --location 'https://${{ secrets.SN_INSTANCE }}.service-now.com/api/now/attachment/file?table_name=sys_attachment&table_sys_id=${{ secrets.SN_SYS_ID }}&file_name=${{ steps.fetch-release.outputs.asset_name }}' \
            --header 'Authorization: Bearer ${{ secrets.SN_BEARER_TOKEN }}' \
            --header 'Content-Type: application/zip' \
            --data-binary "@download_dir/${{ steps.fetch-release.outputs.asset_name }}"
