name: Test on GH actions environment

on:
  push:
    branches:
      - master
  pull_request:
    branches:
      - master
      - releases/*

jobs:
  test:
    runs-on: ${{ matrix.os }}
    strategy:
      matrix:
        os: [windows-latest, ubuntu-latest]
        py: ["3.9", "3.12"]
        qtver: [5.9.9, 6.1.0]
        artifact: [standard]
        include:
          - os: windows-latest
            py: "3.10"
            qtver: 6.1.0
            artifact: binary
          - os: ubuntu-20.04
            py: "3.10"
            qtver: 6.1.0
            artifact: standard
        exclude:
          - os: ubuntu-latest
            py: "3.10"
            qtver: 6.1.0
    steps:
      - uses: actions/checkout@v3
        with:
          fetch-depth: 20
          fetch-tags: true
      - name: Set up Python
        uses: actions/setup-python@v4
        with:
          python-version: ${{ matrix.py }}
      - name: Run pytest
        run: |
          python -m pip install tox-gh-actions build
          tox
      - name: Build and install
        if: matrix.artifact == 'standard'
        run: |
          python -m pip install ./ --user
      - name: Build Standalone binary(linux,mac)
        if: matrix.artifact == 'binary' && matrix.os != 'windows-latest'
        run: |
          python -m venv venv
          source venv/bin/activate
          python -m pip install -U pip wheel setuptools setuptools_scm pyinstaller
          python -m pip install .
          python tools/build_standalone.py
          deactivate
          rm -rf venv
        shell: bash
      - name: Build Standalone binary(windows)
        if: matrix.artifact == 'binary' && matrix.os == 'windows-latest'
        run: |
          python -m venv venv
          venv/Scripts/activate.ps1
          python -m pip install -U pip wheel setuptools setuptools_scm pyinstaller
          python -m pip install .
          python tools/build_standalone.py
          deactivate
          Remove-Item venv -Recurse -Force
        shell: pwsh
      - name: Run aqt
        run: |
          import os
          import pathlib
          import subprocess
          timeout = 300
          os.mkdir("Qt")
          os.chdir("Qt")
          artifact = "${{ matrix.artifact }}"
          platform = "${{ matrix.os }}"
          qtver = "${{ matrix.qtver }}"
          env = os.environ.copy()
          github_workspace = pathlib.Path(env["GITHUB_WORKSPACE"])
          if artifact == "binary":
            if platform.startswith("windows"):
              bin_path = str(github_workspace / "dist" / "aqt.exe")
            else:
              bin_path = (github_workspace / "dist" / "aqt").as_posix()
            prefix = [bin_path, "install"]
          else:
            prefix = ["python", "-m", "aqt", "install"]
          command_line = []
          command_line.extend(prefix)
          if platform == "windows-latest":
            if qtver.startswith('5.15'):
              args = [qtver, "windows", "desktop", "win64_msvc2019_64"]
            elif qtver.startswith('5.14'):
              args = [qtver, "windows", "desktop", "win64_msvc2017_64"]
            elif qtver.startswith('6'):
              args = [qtver, "windows", "desktop", "win64_mingw81"]
            else:
              args = [qtver, "windows", "desktop", "win64_msvc2015_64"]
          elif platform == "macOS-latest":
            args = [qtver, "mac", "desktop", "clang_64"]
          else:
            args = [qtver, "linux", "desktop", "gcc_64"]
          command_line.extend(args)
          command_line.extend(["--archives", "qtbase", "icu", "qt"])
          env["AQT_CONFIG"] = (github_workspace / "ci" / "settings.ini").as_posix()
          env["LOG_CFG"] = (github_workspace / "ci" / "logging.ini").as_posix()
          print("Execute: {}".format(command_line))
          try:
            res = subprocess.run(command_line, timeout=timeout, check=True, env=env)
          except subprocess.CalledProcessError as cpe:
            exit(cpe.returncode)
          assert res.returncode == 0
          if qtver.startswith('6'):
            command_line6 = []
            command_line6.extend(prefix)
            if platform.startswith("ubuntu"):
              command_line6.extend([qtver, "linux", "android", "android_armv7"])
              timeout = 360
            elif platform.startswith("macOS"):
              command_line6.extend([qtver, "mac", "ios", "ios"])
              timeout = 360
            else:
              command_line6.extend([qtver, "windows", "android", "android_armv7"])
              timeout = 360
            print("Execute: {}".format(command_line6))
            try:
              res = subprocess.run(command_line6, timeout=timeout, check=True)
            except subprocess.CalledProcessError as cpe:
              exit(cpe.returncode)
            assert res.returncode == 0
        shell: python
        working-directory: ${{ github.workspace }}
      - name: Test qmake -query
        run: |
          import os
          import pathlib
          from subprocess import CalledProcessError, PIPE, run
          os.chdir("Qt")
          platform = "${{ matrix.os }}"
          qtver = "${{ matrix.qtver }}"
          if platform == "windows-latest":
            if qtver.startswith('5.15'):
              arch_dir = 'msvc2019_64'
            elif qtver.startswith('5.14'):
              arch_dir = 'msvc2017_64'
            elif qtver.startswith('6'):
              arch_dir = 'mingw81_64'
            else:
              arch_dir = 'msvc2015_64'
          elif platform == "macOS-latest":
            arch_dir = 'clang_64'
          else:
            arch_dir = 'gcc_64'
          try:
            res = run([f"{qtver}/{arch_dir}/bin/qmake", "-query"], timeout=15, check=True, stdout=PIPE)
          except CalledProcessError as cpe:
            exit(cpe.returncode)
          if res.returncode == 0:
            qt_prefix_path = pathlib.Path.cwd() / qtver / arch_dir
            for line in res.stdout.splitlines():
              if line.startswith(b'QT_INSTALL_PREFIX'):
                result = line[18:].decode('UTF-8')
                assert qt_prefix_path.samefile(result)
            print('PREFIX {}'.format(result))
            if qtver.startswith('6'):
              if platform == "windows-latest" and qtver.startswith('6'):
                qmake = os.path.join(qtver, 'android_armv7', 'bin', 'qmake.bat')
              elif platform == "macOS-latest" and qtver.startswith('6'):
                qmake = os.path.join(qtver, 'ios', 'bin', 'qmake')
              else:
                qmake = os.path.join(qtver, 'android_armv7', 'bin', 'qmake')
              try:
                res = run([qmake, "-query"], timeout=15, check=True, stdout=PIPE)
              except CalledProcessError as cpe:
                exit(cpe.returncode)
              assert res.returncode == 0
              for line in res.stdout.splitlines():
                if line.startswith(b'QT_INSTALL_PREFIX'):
                  result = line[18:].decode('UTF-8')
              print('PREFIX {}'.format(result))
        shell: python
        working-directory: ${{ github.workspace }}
      - uses: actions/upload-artifact@v2
        if: matrix.artifact == 'binary'
        with:
          name: aqt-${{ matrix.os }}-standalone
          path: dist\aqt*
