name: Runner CD

on:
  push:
    paths:
    - src/runnerversion_block # Change this to src/runnerversion when we are ready.
  
jobs:
  build:
    strategy:
      matrix:
        runtime: [ linux-x64, linux-arm64, linux-arm, win-x64, osx-x64 ]
        include:
        - runtime: linux-x64
          os: ubuntu-latest
          devScript: ./dev.sh

        - runtime: linux-arm64
          os: ubuntu-latest
          devScript: ./dev.sh

        - runtime: linux-arm
          os: ubuntu-latest
          devScript: ./dev.sh

        - runtime: osx-x64
          os: macOS-latest
          devScript: ./dev.sh

        - runtime: win-x64
          os: windows-latest
          devScript: ./dev

    runs-on: ${{ matrix.os }}
    steps:
    - uses: actions/checkout@v1

    # Build runner layout
    - name: Build & Layout Release
      run: |
        ${{ matrix.devScript }} layout Release ${{ matrix.runtime }}
      working-directory: src

    # Run tests
    - name: L0
      run: |
        ${{ matrix.devScript }} test
      working-directory: src
      if: matrix.runtime != 'linux-arm64' && matrix.runtime != 'linux-arm'

    # Create runner package tar.gz/zip
    - name: Package Release
      if: github.event_name != 'pull_request'
      run: |
        ${{ matrix.devScript }} package Release
      working-directory: src

    # Upload runner package tar.gz/zip as artifact.
    # Since each package name is unique, so we don't need to put ${{matrix}} info into artifact name
    - name: Publish Artifact
      if: github.event_name != 'pull_request'
      uses: actions/upload-artifact@v1
      with:
        name: runner-packages
        path: _package

  release:
    needs: build
    runs-on: linux-latest
    steps:

    # Download runner package tar.gz/zip produced by 'build' job
    - name: Download Artifact
      uses: actions/download-artifact@v1
      with:
        name: runner-packages

    # Create ReleaseNote file
    - name: Create ReleaseNote
      id: releaseNote
      uses: actions/github-script@0.3.0
      with:
        github-token: ${{secrets.GITHUB_TOKEN}}
        script: |
          const fs = require('fs');
          // Get runner version from ./src/runnerVersion file
          const versionContent = await github.repos.getContents({
            owner: '${{ github.event.repository.owner.name }}',
            repo: '${{ github.event.repository.name }}',
            path: 'src/runnerversion'
            ref: ${{ github.sha }}
          })
          const runnerVersion = Buffer.from(versionContent.data.content, 'base64').toString()
          console.log("Runner Version ' + runnerVersion)
          core.setOutput('version', runnerVersion);

          // Query GitHub release ensure version is bumped 
          const latestRelease = await github.repos.getLatestRelease({
            owner: '${{ github.event.repository.owner.name }}',
            repo: '${{ github.event.repository.name }}'
          })
          console.log(latestRelease.name)
          const latestReleaseVersion = latestRelease.name.substring(1)
          const vLatest = latestReleaseVersion.split('.')
          const vNew = runnerVersion.split('.')
          let versionBumped = true
          for (let i = 0; i < 3; ++i) {
            var v1 = parseInt(vLatest[i], 10);
            var v2 = parseInt(vNew[i], 10);
            if (v2 > v1) {
              console.log(runnerVersion + " > " + latestReleaseVersion + "(Latest)")
              break
            }
            
            if (v1 > v2) {
              versionBumped = false  
              core.setFailed(runnerVersion + " < " + latestReleaseVersion + "(Latest)")
              break
            }
          }

          // Generate release note
          if (versionBumped) {
            const releaseNoteContent = await github.repos.getContents({
              owner: '${{ github.event.repository.owner.name }}',
              repo: '${{ github.event.repository.name }}',
              path: 'releaseNote.md'
              ref: ${{ github.sha }}
            })
            const releaseNote = Buffer.from(releaseNoteContent.data.content, 'base64').toString().replace("<RUNNER_VERSION>", runnerVersion)
            console.log(releaseNote)
            core.setOutput('note', releaseNote);
          }

    # Create GitHub release
    - uses: actions/create-release@v1
      id: createRelease
      name: Create ${{ steps.releaseNote.outputs.version }} Runner Release
      with:
        tag_name: "v${{ steps.releaseNote.outputs.version }}"
        release_name: "v${{ steps.releaseNote.outputs.version }}"
        body: ${{ steps.releaseNote.outputs.note }}
        prerelease: true

    # Upload release assets
    - name: Upload Release Asset (win-x64)
      uses: actions/upload-release-asset@v1.0.1
      with:
        upload_url: ${{ steps.createRelease.outputs.upload_url }}
        asset_path: ./actions-runner-win-x64-${{ steps.releaseNote.outputs.version }}.zip
        asset_name: actions-runner-win-x64-${{ steps.releaseNote.outputs.version }}.zip
        asset_content_type: application/octet-stream

    - name: Upload Release Asset (linux-x64)
      uses: actions/upload-release-asset@v1.0.1
      with:
        upload_url: ${{ steps.createRelease.outputs.upload_url }}
        asset_path: ./actions-runner-linux-x64-${{ steps.releaseNote.outputs.version }}.zip
        asset_name: actions-runner-linux-x64-${{ steps.releaseNote.outputs.version }}.zip
        asset_content_type: application/octet-stream

    - name: Upload Release Asset (mac-x64)
      uses: actions/upload-release-asset@v1.0.1
      with:
        upload_url: ${{ steps.createRelease.outputs.upload_url }}
        asset_path: ./actions-runner-mac-x64-${{ steps.releaseNote.outputs.version }}.zip
        asset_name: actions-runner-mac-x64-${{ steps.releaseNote.outputs.version }}.zip
        asset_content_type: application/octet-stream

    - name: Upload Release Asset (linux-arm)
      uses: actions/upload-release-asset@v1.0.1
      with:
        upload_url: ${{ steps.createRelease.outputs.upload_url }}
        asset_path: ./actions-runner-linux-arm-${{ steps.releaseNote.outputs.version }}.zip
        asset_name: actions-runner-linux-arm-${{ steps.releaseNote.outputs.version }}.zip
        asset_content_type: application/octet-stream

    - name: Upload Release Asset (linux-arm64)
      uses: actions/upload-release-asset@v1.0.1
      with:
        upload_url: ${{ steps.createRelease.outputs.upload_url }}
        asset_path: ./actions-runner-linux-arm64-${{ steps.releaseNote.outputs.version }}.zip
        asset_name: actions-runner-linux-arm64-${{ steps.releaseNote.outputs.version }}.zip
        asset_content_type: application/octet-stream