# Starter pipeline
# Start with a minimal pipeline that you can customize to build and deploy your code.
# Add steps that build, run tests, deploy, and more:
# https://aka.ms/yaml

pool:
  vmImage: 'ubuntu-latest'

trigger: none

schedules:
- cron: "0 23 * * *"
  displayName: Daily dev run at 10PM UTC (6PM EST)
  branches:
    include:
    - develop

jobs:
- job: Checkmarx
  pool:
    vmImage: 'windows-latest'
  dependsOn: []
  steps:
  - checkout: self
    submodules: false
    fetchDepth: 1
    timeoutInMinutes: 360
  - task: ArchiveFiles@2
    inputs:
      rootFolderOrFile: '$(Build.Repository.LocalPath)'
      includeRootFolder: true
      archiveType: 'zip'
      archiveFile: '$(Build.ArtifactStagingDirectory)/Checkmarx/$(Build.BuildId).zip'
      replaceExistingArchive: true
  - task: PowerShell@2
    inputs:
      pwsh: true
      targetType: 'inline'
      script: |
        $loginData = @{
            userName = "$(CheckMarxUser)";
            password = "$(CheckMarxPass)";
            grant_type = "password";
            scope = "sast_rest_api";
            client_id = "resource_owner_client";
            client_secret = "014DF517-39D1-4453-B7B3-9930C563627C";
          }
        Write-Host "`nAttempting to authenticate to Checkmarx...`n"
        
        try {
        $login = Invoke-RestMethod "https://blackbaud.checkmarx.net/CxRestapi/auth/identity/connect/token" -Method Post -Body $loginData;
        }
        catch{
        
            Write-Host "CHECKMARX ERROR: Failed to authenticate to Checkmarx, `n StatusCode:" $_.Exception.Response.StatusCode.value__
            exit 1 
        }
        Write-Host "`nSuccessfully authenticated to Checkmarx`n"
        
        $access_token = $login.access_token
        
        $bearerToken = "Bearer "+ $login.access_token
        
        $headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]";
        $headers.Add("Authorization",$bearerToken)
        $headers.add("Content-Type", "application/json")
        
        try {
        $projects = Invoke-RestMethod "https://blackbaud.checkmarx.net/cxrestapi/projects" -Method Get -Headers $headers
        }
        catch {
            Write-Host "CHECKMARX ERROR: Failed to get List of Projects, `n StatusCode:" $_.Exception.Response.StatusCode.value__
            exit 1 
        }
        
        $projectName = "$(CheckMarxProjectName)"
        Write-Output "`nAttempting to locate [ $(CheckMarxProjectName) ] in CheckMarx"
        
        $specificProject = $projects | Where-Object { $_.name -eq $projectName } 
        if (-not ( $specificProject.name -eq $projectName) ) {
          Write-Output "`nProject not registered within Checkmarx.  Aborting scan."
          exit 0
        }
        $cxProjectName = $specificProject.name
        
        $proj_id = $specificProject.id
        
        Write-Output "`nSuccessfully located [ $cxProjectName ]in CheckMarx`n"
        
        $zipped_file = "$(Build.ArtifactStagingDirectory)" + "/Checkmarx/$(Build.BuildId).zip"
        
        
        $fileUploadHeaders = New-Object "System.Collections.Generic.Dictionary[[String],[String]]";
        $fileUploadHeaders.Add("Authorization",$bearerToken)
        $fileUploadHeaders.add("Content-Type", "multipart/form-data")
        
        $Form = @{
            name = '$(Build.BuildId).zip'
            zippedSource = Get-Item -Path "$zipped_file"
        }
        
        try{
        $fileUpload = Invoke-RestMethod -Uri "https://blackbaud.checkmarx.net/cxrestapi/projects/$proj_id/sourceCode/attachments" -Method Post -Form $Form -Headers $fileUploadHeaders -ErrorVariable RespErr
        }
        catch {
          Write-Host "`nCHECKMARX ERROR: Failed to successfully upload source code, `n StatusCode:" $_.Exception.Response.StatusCode.value__ 
          Write-Host "`nCHECKMARX ERROR: " $_.Exception.Message
          exit 1
        }
        Write-Output "`nSuccessfully uploaded source code to CheckMarx`n"
        
        $sendscanData = @{
        projectId = "$proj_id";
        isIncremental = "true";
        isPublic = "true";
        forceScan = "true";
        comment = "Scanning Repo: $projectName,  Build: $(Build.BuildNumber) BuildId: $(Build.BuildId)";
        }
        
        $jsonScan = ConvertTo-Json $sendscanData
        
        Write-Output "`nTriggering Checkmarx scan...`n"
        
        try {
        $startScan = Invoke-RestMethod -Uri "https://blackbaud.checkmarx.net/CxRestapi/sast/scans" -Method Post -Body $jsonScan -Headers $headers -ErrorVariable RespErr;
        }
        catch 
        {
            Write-Host "`nCHECKMARX ERROR: Failed to successfully trigger a scan, `n StatusCode:" $_.Exception.Response.StatusCode.value__
        
            exit 1
        }
        
        Write-Output "`nSuccessfully triggered Checkmarx scan`n"



- job: WhiteSource
  dependsOn: []
  steps:
  - checkout: self
    submodules: true
    fetchDepth: 1
    timeoutInMinutes: 360

  - task: NodeTool@0
    inputs:
      versionSpec: '14.x'
    displayName: 'Install Node.js v14'

  - task: Npm@1
    inputs:
      command: 'ci'

  - script: |
      #!/bin/bash

      echo "#GrantsConnect-UI Whitesource configuration file
      #Whitesource Config File Documentation
      #https://whitesource.atlassian.net/wiki/spaces/WD/pages/489160834/Unified+Agent+Configuration+File+Parameters

      checkPolicies=false
      forceCheckAllDependencies=false
      forceUpdate=false
      forceUpdate.failBuildOnPolicyViolation=false
      offline=false
      scanComment=

      wss.url=https://app.whitesourcesoftware.com/agent

      npm.resolveDependencies=true
      bower.resolveDependencies=false
      nuget.resolveDependencies=false
      python.resolveDependencies=false
      maven.resolveDependencies=false
      paket.resolveDependencies=false
      go.resolveDependencies=false
      ruby.resolveDependencies = false
      sbt.resolveDependencies=false
      php.resolveDependencies=false
      html.resolveDependencies=false
      cocoapods.resolveDependencies=false
      gradle.resolveDependencies=false
      requireKnownSha1=false

      apiKey=$(WhiteSourceAPIKey)
      projectName=GrantsConnect-UI
      productName=GrantsConnect-UI

      includes= **/*.js
      excludes=**/*sources.jar **/*javadoc.jar

      case.sensitive.glob=false
      followSymbolicLinks=true
      " > agent-config-output.config


      curl -LJO https://github.com/whitesource/unified-agent-distribution/releases/latest/download/wss-unified-agent.jar

      java -jar wss-unified-agent.jar -c agent-config-output.config

      rm agent-config-output.config
