
parameters:
- name: cmakeArgs
  type: string
  default: ''
- name: sourceDir
  type: string
  default: ''
- name: workDir
  type: string
  default: $(DEV)
- name: condition
  type: string
  default: and(succeeded(), ne(variables.CACHE_RESTORED, 'true'))
- name: installCommand
  type: string
  default: 'make install'

steps:
- script: |
    set -ex

    pushd ${{ parameters.sourceDir }}
    mkdir -p build
    pushd build
    
    # Invoke cmake in the most correctest way I've could find while try and erroring:
    #
    # The biggest pain point is that CMake does not seem to respect our existing cross compilation CFLAGS and LDFLAGS.
    # Hence we are passing them manually, once via Android flags and once for "Required" flags. The latter is necessary
    # to let cmake correctly probe for any existing header, function, library, etc.
    # Watch out: Sometimes the flags are passed as ;-limited list!
    cmake -G "Unix Makefiles" \
        -DCMAKE_MAKE_PROGRAM=make \
        -DCMAKE_TOOLCHAIN_FILE=${NDK}/build/cmake/android.toolchain.cmake \
        -DCMAKE_BUILD_TYPE=RelWithDebInfo \
        -DANDROID_NATIVE_API_LEVEL=${ANDROID_API} \
        -DANDROID_ABI=${ANDROID_ABI_CMAKE} \
        -DANDROID_TOOLCHAIN=${CC} \
        -DANDROID_NDK=${NDK} \
        -DANDROID_COMPILER_FLAGS="${CFLAGS// /;}" \
        -DANDROID_LINKER_FLAGS="${LDFLAGS// /;}" \
        -DANDROID_STL="c++_shared" \
        -DCMAKE_REQUIRED_FLAGS="${CFLAGS}" \
        -DCMAKE_REQUIRED_LINK_OPTIONS="${LDFLAGS// /;}" \
        -DCMAKE_INSTALL_PREFIX=${PREFIX} \
        -DCMAKE_STAGING_PREFIX=${PREFIX} \
        -DCMAKE_VERBOSE_MAKEFILE=1 \
        -DBUILD_SHARED_LIBS=1 \
        -DLIB_SUFFIX= \
        ${{ parameters.cmakeArgs }} ..
    make -j$((`nproc`+1))
    ${{ parameters.installCommand }}
    popd
    popd
  displayName: 'Compile ${{ parameters.sourceDir }}'
  workingDirectory: ${{ parameters.workDir }}
  condition: ${{ parameters.condition }}

- script: |
    ls -la ${{ parameters.sourceDir }}/build/CMakeFiles/
    cat ${{ parameters.sourceDir }}/build/CMakeFiles/CMakeError.log
    cat ${{ parameters.sourceDir }}/build/CMakeFiles/CMakeOutput.log
    true
  displayName: 'Print ${{ parameters.sourceDir }} Cmake Error Log'
  condition: or(${{ parameters.condition }}, failed())
  workingDirectory: ${{ parameters.workDir }}
