#
# CMake based build for Audacity
#
name: CMake Build

#
# Only execute on "git push" actions
#
on:
  push:
    # Remove the "#" from the next 2 lines if you need to disable this action
    #branches:
    #  - disable
  pull_request:
    # Remove the "#" from the next 2 lines if you need to disable this action
    #branches:
    #  - disable

#
# Global environment variables
#
env:
  WXURL: https://github.com/audacity/wxWidgets
  WXREF: audacity-fixes-3.1.3
  WXWIN: ${{ github.workspace }}/wxwin

#
# Define our job(s)
#
jobs:
  build:
    name: ${{ matrix.config.name }}
    runs-on: ${{ matrix.config.os }}
    strategy:
      fail-fast: false
      matrix:
        config:
        - {
            name: "Windows_32bit",
            os: windows-latest,
            generator: "Visual Studio 16 2019",
            platform: "Win32"
          }
        - {
            name: "Windows_64bit",
            os: windows-latest,
            generator: "Visual Studio 16 2019",
            platform: "x64"
          }
        - {
            name: "Ubuntu_18.04",
            os: ubuntu-18.04,
            generator: "Unix Makefiles"
          }
        - {
            name: "macOS",
            os: macos-latest,
            generator: "Xcode"
          }

    steps:
    # =========================================================================
    # SHARED: Checkout source
    # =========================================================================
    - name: Checkout
      uses: actions/checkout@v2
    #  with:
    #    ref: master

    # =========================================================================
    # SHARED: Retrieve git hashes and set up for cache
    # =========================================================================
    - name: Setup cache
      shell: bash
      run: |
        set -x

        # Get latest wxWidgets commit hash
        wxhash=$(git ls-remote "${WXURL}" "${WXREF}" | awk 'NR==1 {print $1}')

        # Build the cache key
        wxhash="wx_${wxhash}_${RUNNER_OS}_${{matrix.config.platform}}"

        # Export the commit hash to further steps
        echo "::set-env name=WXHASH::${wxhash}"

        # Get the short hash
        shorthash=$(git show -s --format='%h')

        # Export the short hash for the upload step
        echo "::set-env name=SHORTHASH::${shorthash}"

        # Export the destination directory name
        echo "::set-env name=DEST::${{matrix.config.name}}_${shorthash}"

    # =========================================================================
    # SHARED: Create and/or retrieve wxWidgets cached build
    # =========================================================================
    - name: Populate cache
      id: cache
      uses: actions/cache@v1
      with:
        # Increment the number at the end to force recreation of the cache
        key: ${{ env.WXHASH }}.8
        path: ${{ env.WXWIN }}

    # =========================================================================
    # WINDOWS: Build (for all versions of Windows)
    # =========================================================================
    - name: Build for Windows
      if: startswith( matrix.config.os, 'windows' )
      shell: bash
      run: |
        set -x

        # Build wxWidgets if needed
        if [ ! -e "${WXWIN}" ]
        then
          # Clone the wxWidgets repo
          git clone --depth 1 --recurse-submodules -b "${WXREF}" "${WXURL}" "wxroot"

          # Use cmake since it defines the MSVC enviornment for us
          cmake -S "wxroot" \
                -B "wxroot" \
                -G "${{matrix.config.generator}}" \
                -A "${{matrix.config.platform}}"

          # Build
          cmake --build "wxroot" --config Release --verbose

          # Install to the cached path
          cmake --install "wxroot" --config Release --prefix "${WXWIN}"

          # On Windows, we need zlib for libid3tag
          mkdir -p "${WXWIN}/src"
          cp -a "wxroot/lib" "${WXWIN}/"
          cp -a "wxroot/src/zlib" "${WXWIN}/src"
        fi

        # Convert to CMake path
        export WXWIN="${WXWIN//\\//}"

        # Configure Audacity
        #
        # The wxWidgets_USE_REL_AND_DBG is needed because,
        # on Github, we only build the Release version of
        # wxWidgets and the FindwxWidgets CMake module
        # defaults to looking for both.  If either of them
        # isn't found, then it doesn't provides the required
        # library information.  This is only a concern for
        # Windows.
        cmake -S . \
              -B build \
              -G "${{matrix.config.generator}}" \
              -A ${{matrix.config.platform}} \
              -D wxWidgets_USE_REL_AND_DBG=NO

        # Build Audacity
        cmake --build build --config Release --verbose

        # "Install" Audacity
        mkdir -p "${DEST}"
        cp -a build/bin/Release/* "${DEST}"
        rm -f "${DEST}"/{*.iobj,*.ipdb}

        # Create artifact (zipped as Github actions don't preserve permissions)
        cmake -E tar c "${GITHUB_SHA}.zip" --format=zip "${DEST}"

    # =========================================================================
    # MACOS: Build (for all versions of MacOS)
    # =========================================================================
    - name: Build for macOS
      if: startswith( matrix.config.os, 'macos' )
      shell: bash
      run: |
        set -x

        # Setup environment
        export PATH="/usr/local/bin:${PATH}"
        export DYLD_LIBRARY_PATH="/usr/local/lib"

        # Install required packages
        brew install gettext
        brew link --force gettext

        # Build wxWidgets if needed
        if [ ! -e "${WXWIN}" ]
        then
          # Clone the wxWidgets repo
          git clone --depth 1 --recurse-submodules -b "${WXREF}" "${WXURL}" "wxroot"

          # Make sure our flags are included
          export CXX="g++ -std=c++1z -stdlib=libc++"
          export LD="g++ -std=c++1z -stdlib=libc++"

          # The cmake build produces an incorrect wx-config script, so use
          # the plain old configure/make
          cd wxroot
          ./configure --prefix=/usr/local \
                      --enable-debug=no \
                      --enable-macosx-arch="x86_64" \
                      --enable-shared=yes \
                      --enable-unicode=yes \
                      --enable-universal_binary=no \
                      --enable-webkit=no \
                      --enable-webviewwebkit=no \
                      --with-expat=builtin \
                      --with-flavour="release" \
                      --with-libjpeg=builtin \
                      --with-libpng=builtin \
                      --with-libtiff=builtin \
                      --with-macosx-version-min="10.7" \
                      --with-regex=builtin \
                      --with-zlib=builtin \
                      --without-liblzma

          # Build and install to cached path
          make -j $(sysctl -n hw.ncpu) install DESTDIR="${WXWIN}"
          cd ..

          # Clean up
          unset CXX LD
        fi

        # "Install" wxWidgets
        sudo cp -a "${WXWIN}"/usr/* /usr

        # Configure Audacity
        cmake -S . \
              -B build \
              -G "${{matrix.config.generator}}" \
              -D audacity_use_pch=no

        # Build Audacity
        cmake --build build --config Release

        # "Install" Audacity
        mkdir -p "${DEST}"
        cp -a build/bin/Release/ "${DEST}"

        # Create artifact (zipped as Github actions don't preserve permissions)
        cmake -E tar c "${GITHUB_SHA}.zip" --format=zip "${DEST}"

    # =========================================================================
    # UBUNTU: Build (for all versions of Ubuntu)
    # =========================================================================
    - name: Build for Ubuntu
      if: startswith( matrix.config.os, 'ubuntu' )
      shell: bash
      run: |
        set -x

        # Setup environment
        export PATH="/usr/local/bin:${PATH}"
        export LD_LIBRARY_PATH="/usr/local/lib"

        # Install required packages
        sudo apt-get update -y
        sudo apt-get install -y libgtk2.0-dev libasound2-dev gettext
        sudo apt-get remove -y ccache

        # Build wxWidgets if needed
        if [ ! -e "${WXWIN}" ]
        then
          # Clone the wxWidgets repo
          git clone --depth 1 --recurse-submodules -b "${WXREF}" "${WXURL}" "wxroot"

          # Install additional required package
          sudo apt-get install -y autoconf automake

          # The cmake build produces an incorrect wx-config script, so use
          # the plain old configure
          cd wxroot
          ./configure --with-gtk

          # Build and install to cached path
          make -j $(nproc) install DESTDIR="${WXWIN}"
          cd ..
        fi

        # "Install" wxWidgets
        sudo cp -a "${WXWIN}"/* /

        # Configure Audacity
        cmake -S . \
              -B build \
              -G "${{matrix.config.generator}}" \
              -D audacity_use_pch=no

        # Build Audacity
        cmake --build build --config Release

        # "Install" Audacity
        cmake --install build --config Release --prefix "${DEST}"

        # Create the lib directory
        mkdir -p ${DEST}/lib

        # Copy over wxWidgets libs
        ldd ${DEST}/bin/audacity
        for lib in $(ldd ${DEST}/bin/audacity | awk '/libwx/{print $3}')
        do
           echo ${lib}
           ldd ${lib} | awk '/libwx/{print $3}'
        done | sort -u | xargs cp -n -H -t ${DEST}/lib

        # Create wrapper script
        cat >"${DEST}/audacity" <<"EOF"
        #!/bin/sh
        export LD_LIBRARY_PATH="${0%/*}/lib:${LD_LIBRARY_PATH}"
        "${0%/*}/bin/audacity"
        EOF
        chmod +x "${DEST}/audacity"

        # Create artifact (zipped as Github actions don't preserve permissions)
        cmake -E tar c "${GITHUB_SHA}.zip" --format=zip "${DEST}"

    # =========================================================================
    # SHARED: Attach the artifact to the workflow results
    # =========================================================================
    - name: Upload artifact
      uses: actions/upload-artifact@v1
      with:
        name: ${{ matrix.config.name }}_${{ env.SHORTHASH }}
        path: ${{ github.sha }}.zip

