# BespokeSynth Azure Pipelines script

trigger:
  - main

variables:
  - group: mac-signing
  - group: libraries

pr:
  - main

jobs:
  - job: Build
    variables:
      isBuild: True
    strategy:
      matrix:
        macOS-x64:
          imageName: 'macos-14'
          isMac: True
          cmakeArguments: "-GXcode -D\"CMAKE_OSX_ARCHITECTURES='arm64;x86_64'\" -DBESPOKE_SIGN_AS='$(MAC_SIGNING_CERT)' -DBESPOKE_PYTHON_ROOT='/Library/Frameworks/Python.framework/Versions/3.10'"
          cmakeTarget: "BespokeSynth"
        windows-x64:
          imageName: 'windows-2019'
          isWindows: True
          cmakeArguments: "-A x64"
          cmakeTarget: "BespokeSynth"
        code-formatting:
          imageName: 'ubuntu-20.04'
          isLinux: True
          cmakeArguments: ""
          cmakeTarget: "code-quality-pipeline-checks"
        linux-x64:
          imageName: 'ubuntu-20.04'
          isLinux: True
          cmakeArguments: "-GNinja"
          cmakeTarget: "BespokeSynth"

    pool:
      vmImage: $(imageName)

    steps:
      - checkout: self
        fetchDepth: 5
        # submodules: recursive # can't do submodules here b'cuz depth=1 fails with Github

      - bash: |
          echo "BUILD REASON   = " $(Build.Reason)
          echo "cmakeArguments = " $(cmakeArguments)

          if [ $(Build.Reason) == "PullRequest" ] || [ $(cmakeTarget) == "code-quality-pipeline-checks" ]; then
            export CMAKE_CONFIG=Debug
            export CMAKE_TARGET=$(cmakeTarget)
            echo "##vso[task.setvariable variable=CMAKE_CONFIG]Debug"
            echo "##vso[task.setvariable variable=CMAKE_CONFIG;isOutput=true]Debug"
            echo "##vso[task.setvariable variable=CMAKE_TARGET]$(cmakeTarget)"
            echo "##vso[task.setvariable variable=CMAKE_TARGET;isOutput=true]$(cmakeTarget)"
          else
            export CMAKE_CONFIG=Release
            export CMAKE_TARGET=nightly-package
            echo "##vso[task.setvariable variable=CMAKE_CONFIG]Release"
            echo "##vso[task.setvariable variable=CMAKE_CONFIG;isOutput=true]Release"
            echo "##vso[task.setvariable variable=CMAKE_TARGET]nightly-package"
            echo "##vso[task.setvariable variable=CMAKE_TARGET;isOutput=true]nightly-package"
          fi

          echo "cmakeConfig    = " $CMAKE_CONFIG
          echo "cmakeTarget    = " $CMAKE_TARGET
        displayName: all - details on build

      - bash: |
          git submodule update --init --recursive --depth 1
        displayName: all - submodule init


      - bash: |
          set -e

          sudo apt-get update

          sudo apt-get install -y \
              devscripts \
              libxcb-cursor-dev \
              libxcb-keysyms1-dev \
              libxcb-util-dev \
              libxkbcommon-dev \
              libxkbcommon-x11-dev \
              ninja-build \
              xcb \
              libgtk-3-dev \
              libwebkit2gtk-4.0 \
              libwebkit2gtk-4.0-dev \
              libcurl4-openssl-dev \
              alsa \
              alsa-tools \
              libasound2-dev \
              libjack-dev \
              libfreetype6-dev \
              libxinerama-dev \
              libxcb-xinerama0 \
              libxinerama1 \
              x11proto-xinerama-dev \
              libxrandr-dev \
              libgl1-mesa-dev \
              libxcursor-dev \
              libxcursor1 \
              libxcb-cursor-dev \
              libxcb-cursor0 \
              libusb-1.0.0-dev \
              patchelf

        condition: variables.isLinux
        displayName: linux - run apt-get

      - script: |
          npm install -g appdmg
          wget https://www.python.org/ftp/python/3.10.0/python-3.10.0post2-macos11.pkg
          sudo installer -pkg python-3.10.0post2-macos11.pkg -target /
        condition: variables.isMac
        displayName: mac - install dependencies needed for distribution build

      - task: InstallAppleCertificate@2
        inputs:
          certSecureFile: 'bespoke_dev_id_app.p12'
          certPwd: '$(MAC_EXPORTED_CERT_PW)'
        condition: variables.isMac

      - task: InstallAppleCertificate@2
        inputs:
          certSecureFile: 'bespoke_dev_id_inst.p12'
          certPwd: '$(MAC_EXPORTED_CERT_PW)'
        condition : variables.isMac
      
      - task: DownloadSecureFile@1
        name: extra_apis
        inputs:
          secureFile: extra_apis.zip
        condition: ne(variables['Build.Reason'], 'PullRequest')

      - bash: |
          mv "$(extra_apis.secureFilePath)" "$(Build.SourcesDirectory)"
        displayName: move extra_apis
        condition: ne(variables['Build.Reason'], 'PullRequest')

      - task: ExtractFiles@1
        inputs:
          archiveFilePatterns: 'extra_apis.zip'
          destinationFolder: '$(Build.SourcesDirectory)/extra_apis'
        condition: ne(variables['Build.Reason'], 'PullRequest')

      - bash: |
          set -e
          echo Building with BUILD_TYPE = $CMAKE_CONFIG and arguments = $(cmakeArguments)
          cmake -Bbuild $(cmakeArguments) $(LIBRARY_PATHS) -DCMAKE_BUILD_TYPE=$CMAKE_CONFIG -DBESPOKE_PORTABLE=True -DBESPOKE_NIGHTLY=True
        displayName: all - configure with cmake for nightly
        condition: ne(variables['Build.Reason'], 'PullRequest')

      - bash: |
          set -e
          echo Building with BUILD_TYPE = $CMAKE_CONFIG and arguments = $(cmakeArguments)
          cmake -Bbuild $(cmakeArguments) -DCMAKE_BUILD_TYPE=$CMAKE_CONFIG -DBESPOKE_PORTABLE=True -DBESPOKE_WERROR=True
        displayName: all - configure with cmake for PR
        condition: eq(variables['Build.Reason'], 'PullRequest')

      - bash: |
          set -e
          echo Building with TARGET = $CMAKE_TARGET
          cmake --build build --config $CMAKE_CONFIG --target $CMAKE_TARGET
        displayName: mac - build with cmake
        condition: variables.isMac
        env:
          MAC_INSTALLING_CERT: $(MAC_INSTALLING_CERT)
          MAC_SIGNING_1UPW: $(MAC_SIGNING_1UPW)
          MAC_SIGNING_CERT: $(MAC_SIGNING_CERT)
          MAC_SIGNING_ID: $(MAC_SIGNING_ID)
          MAC_SIGNING_TEAM: $(MAC_SIGNING_TEAM)

      - bash: |
          set -e
          echo Building with TARGET = $CMAKE_TARGET
          cmake --build build --config $CMAKE_CONFIG --target $CMAKE_TARGET
        displayName: win - build with cmake
        condition: variables.isWindows

      - bash: |
          set -e
          echo Building with TARGET = $CMAKE_TARGET
          cmake --build build --config $CMAKE_CONFIG --target $CMAKE_TARGET
        displayName: lin - build with cmake
        condition: variables.isLinux

      - bash: |
           set -e
           echo Copying build output from build/Source/BespokeSynth_artefacts/Release to windows_nightly_artefact
           cp -R build/Source/BespokeSynth_artefacts/Release windows_nightly_artefact
        condition: and(variables.isWindows,
                       ne(variables['Build.Reason'], 'PullRequest'),
                       ne(variables['cmakeTarget'], 'code-quality-pipeline-checks'))
        displayName: win - copy win artifact

      - powershell: |
          echo Compressing build output from windows_nightly_artefact to build/nightly
          mkdir build/nightly
          Compress-Archive -Path windows_nightly_artefact/* -DestinationPath build/nightly/BespokeSynth-Windows.zip
        condition: and(variables.isWindows,
                       ne(variables['Build.Reason'], 'PullRequest'),
                       ne(variables['cmakeTarget'], 'code-quality-pipeline-checks'))
        displayName: win - compress win artifact

      - bash: |
           set -e
           echo Compressing build output from build/Source/BespokeSynth_artefacts/Release to build/nightly
           mkdir build/nightly
           tar -cvzf build/nightly/BespokeSynth-Linux.tar.gz build/Source/BespokeSynth_artefacts/Release
        condition: and(variables.isLinux,
                       ne(variables['Build.Reason'], 'PullRequest'),
                       ne(variables['cmakeTarget'], 'code-quality-pipeline-checks'))
        displayName: lin - compress lin artifact
        
      - bash: |
          mkdir -p stage_git/git_info
          git log -1 --pretty=format:'%h : %s - %an' > stage_git/git_info/git_nightly_log_display
          git log -1 --pretty=format:'%h : %s%n%aD%n%an%n%n%B' > stage_git/git_info/git_nightly_log_long_display
          git log -5 --pretty=format:'%h : %s - %an' > stage_git/git_info/git_nightly_recent_five
          git log -1 --pretty=format:'%h' > stage_git/git_info/git_nightly_log_hash
          cat stage_git/git_info/*
        condition: variables.isLinux
        displayName: lin - make git log info

      - task: PublishPipelineArtifact@0
        inputs:
          artifactName: 'GIT_INFO'
          targetPath: 'stage_git/'
        condition: variables.isLinux
        displayName: lin - publish the git info

      - task: PublishPipelineArtifact@0
        inputs:
          artifactName: 'INSTALLER_MAC_NIGHTLY'
          targetPath: 'build/nightly'
        condition: and(variables.isMac,
                       ne(variables['Build.Reason'], 'PullRequest'),
                       ne(variables['cmakeTarget'], 'code-quality-pipeline-checks'))
        displayName: mac - publish mac artifact

      - task: PublishPipelineArtifact@0
        inputs:
          artifactName: 'INSTALLER_WIN_NIGHTLY'
          targetPath: 'build/nightly'
        condition: and(variables.isWindows,
                       ne(variables['Build.Reason'], 'PullRequest'),
                       ne(variables['cmakeTarget'], 'code-quality-pipeline-checks'))
        displayName: win - publish win artifact

      - task: PublishPipelineArtifact@0
        inputs:
          artifactName: 'INSTALLER_LIN_NIGHTLY'
          targetPath: 'build/nightly'
        condition: and(variables.isLinux,
                       ne(variables['Build.Reason'], 'PullRequest'),
                       ne(variables['cmakeTarget'], 'code-quality-pipeline-checks'))
        displayName: lin - publish lin artifact



  - job: Release
    dependsOn: Build
    condition: and(succeeded(), ne(variables['Build.Reason'], 'PullRequest'))
    pool:
      vmImage: 'macos-12'

    steps:
    - checkout: self
      persistCredentials: true

    - task: DownloadSecureFile@1
      inputs:
        secureFile: discord-nightly.webhook

    - task: DownloadPipelineArtifact@0
      inputs:
        artifactName: 'INSTALLER_MAC_NIGHTLY'
        targetPath: $(System.DefaultWorkingDirectory)

    - task: DownloadPipelineArtifact@0
      inputs:
        artifactName: 'INSTALLER_WIN_NIGHTLY'
        targetPath: $(System.DefaultWorkingDirectory)

    - task: DownloadPipelineArtifact@0
      inputs:
        artifactName: 'INSTALLER_LIN_NIGHTLY'
        targetPath: $(System.DefaultWorkingDirectory)

    - task: DownloadPipelineArtifact@0
      inputs:
        artifactName: 'GIT_INFO'
        targetPath: $(System.DefaultWorkingDirectory)

    - bash: |
        set -e
        set -x

        short_hash=`git rev-parse --short=7 HEAD`

        mkdir -p releases
        ls $(System.DefaultWorkingDirectory)/git_info
        
        mv *.zip *.dmg *.gz releases

        cd releases
        for f in *.*; do mv -- "$f" "${f%.*}_${short_hash}_$(date +%F).${f##*.}"; done
        cd ..

        echo "bespoke nightly build $(date +%F)" >> releases/ReleaseNotes.md
        echo " " >> releases/ReleaseNotes.md
        echo "<pre>" >> releases/ReleaseNotes.md
        cat $(System.DefaultWorkingDirectory)/git_info/git_nightly_recent_five >> releases/ReleaseNotes.md
        echo " " >> releases/ReleaseNotes.md
        echo "</pre>" >> releases/ReleaseNotes.md

        echo "---------------"
        cat releases/ReleaseNotes.md
        echo "---------------"

        ls -alFh releases
      displayName: Prepare Release

    - task: GitHubRelease@0
      displayName: "Create Github Nightly Release"
      inputs:
        gitHubConnection: BespokeSynthPublish
        repositoryName: BespokeSynth/BespokeSynth
        action: 'edit'
        tag: Nightly
        target: '$(Build.SourceVersion)'
        addChangeLog: false
        assetUploadMode: 'delete'
        releaseNotesFile: $(System.DefaultWorkingDirectory)/releases/ReleaseNotes.md
        assets: $(System.DefaultWorkingDirectory)/releases/*.*
        isPreRelease: true

    - bash: |
        curl -i -H "Accept: application/json" -H "Content-Type:application/json" -X POST --data "{\"content\": \"a bespoke nightly build is available. get it here:\nhttps://github.com/BespokeSynth/BespokeSynth/releases/tag/Nightly\"}" `cat $AGENT_TEMPDIRECTORY/discord-nightly.webhook`
      displayName: Tell Discord