name: CI

on:
  workflow_call:
    inputs:
      sasmodels_ref:
        description: 'Branch or tag for sasmodels (default: master)'
        required: false
        type: string
      sasdata_ref:
        description: 'Branch or tag for sasdata (default: master)'
        required: false
        type: string
  workflow_dispatch:
    inputs:
      sasmodels_ref:
        description: 'Branch or tag for sasmodels (default: master)'
        required: false
        type: string
      sasdata_ref:
        description: 'Branch or tag for sasdata (default: master)'
        required: false
        type: string
  pull_request:
  push:

defaults:
  run:
    shell: bash

env:
  # Version of Python that will be used in the release builds
  RELEASE_PYVER: "3.13"
  # Determine if this CI is being done during the release polishing steps
  RELEASE_BRANCH_BUILD: ${{
      (
        (github.event_name == 'push' && startsWith(github.ref, 'refs/heads/release')) ||
        (github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v')) ||
        (github.event_name == 'pull_request' && startsWith(github.base_ref, 'refs/heads/release'))
      ) && 'true' || '' }}

  # The test-installer job can use an old existing image rather than the most
  # recently built image; the 'needs' can be commented out to allow the
  # test-installer job to run independently (and therefore faster)
  INSTALLER_USE_OLD_IMAGE: false
  INSTALLER_OLD_RUNID: 3204825457
  # The test-installer job can run with the pyinstaller debug bundle
  INSTALLER_USE_DEBUG: false

jobs:

  ruff:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6
      - uses: astral-sh/ruff-action@v3
        with:
          version: "latest"
          args: "--version"
      - run: ruff check --diff --exit-zero
      - run: ruff check --fix-only --exit-non-zero-on-fix
      - uses: pre-commit-ci/lite-action@v1.1.0
        if: always()
        with:
          msg: '[pre-commit.ci lite] apply automatic fixes for ruff linting errors'

  set-dependency-refs:
    needs: [ruff]
    name: Set dependency refs
    runs-on: ubuntu-latest
    outputs:
      dependency-matrix-json: ${{ steps.set-refs.outputs.dependency_matrix }}
    steps:
      - name: Set up Python
        uses: actions/setup-python@v6
        with:
          python-version: ${{ env.RELEASE_PYVER }}

      - name: Set dependency refs and generate matrix
        id: set-refs
        run: |
          # Get refs from inputs (workflow_call or workflow_dispatch) or default to master
          SASMODELS_REF="${{ inputs.sasmodels_ref || 'master' }}"
          SASDATA_REF="${{ inputs.sasdata_ref || 'master' }}"
          echo "Using sasmodels ref: $SASMODELS_REF"
          echo "Using sasdata ref: $SASDATA_REF"
          
          # Generate dependency matrix as JSON using Python for proper escaping
          python3 << 'PYTHON_SCRIPT'
          import json
          import os
          
          sasmodels_ref = os.environ.get('SASMODELS_REF', 'master')
          sasdata_ref = os.environ.get('SASDATA_REF', 'master')
          
          dependency_matrix = [
              {"name": "sasdata", "url": "https://github.com/SasView/sasdata.git", "ref": sasdata_ref},
              {"name": "sasmodels", "url": "https://github.com/SasView/sasmodels.git", "ref": sasmodels_ref}
          ]
          
          with open(os.environ['GITHUB_OUTPUT'], 'a') as f:
              f.write(f"dependency_matrix={json.dumps(dependency_matrix)}\n")
          PYTHON_SCRIPT
        env:
          SASMODELS_REF: ${{ inputs.sasmodels_ref || 'master' }}
          SASDATA_REF: ${{ inputs.sasdata_ref || 'master' }}

  matrix:
    needs: [ruff]
    name: Generate test matrix

    #if: false    # uncomment to prevent the rest of the workflow running

    runs-on: ubuntu-latest

    # Stop existing workflows for matching branches and pull requests
    concurrency:
      group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
      cancel-in-progress: true

    outputs:
      test-matrix-json: ${{ steps.set-matrix.outputs.test_matrix }}
      installer-matrix-json: ${{ steps.set-matrix.outputs.installer_matrix }}

    steps:
      - name: Set up Python
        uses: actions/setup-python@v6
        with:
          python-version: ${{ env.RELEASE_PYVER }}

      - uses: actions/checkout@v6

      - name: Generate job configuration matrix
        id: set-matrix
        env:
          GITHUB_EVENT_NAME: ${{ github.event_name }}
        run: python .github/workflows/matrix.py >> $GITHUB_OUTPUT


  build-dependencies:
    needs: [ruff, set-dependency-refs]
    runs-on: ubuntu-latest

    strategy:
      fail-fast: false
      matrix:
        dependency: ${{ fromJson(needs.set-dependency-refs.outputs.dependency-matrix-json) }}

    name: Build wheel ${{ matrix.dependency.name }}

    steps:
      - name: Set up Python
        uses: actions/setup-python@v6
        with:
          python-version: ${{ env.RELEASE_PYVER }}

      ### Check if this wheel is already cached

      - name: Get latest commit SHA for ${{ matrix.dependency.name }}
        id: get-sha
        run: |
          REF="${{ matrix.dependency.ref }}"
          URL="${{ matrix.dependency.url }}"

          # Try as branch first, then as tag
          SHA=$(git ls-remote "$URL" "refs/heads/$REF" | cut -f1)
          if [ -z "$SHA" ]; then
            SHA=$(git ls-remote "$URL" "refs/tags/$REF" | cut -f1)
          fi

          echo "Using $REF ($SHA)"
          echo "sha=$SHA" >> $GITHUB_OUTPUT

      - name: Obtain wheel cache
        id: cache-wheel
        uses: actions/cache@v5
        with:
          path: ~/.cache/cache-wheel/
          key: wheel-${{ matrix.dependency.name }}-${{ steps.get-sha.outputs.sha }}

      ### Build the wheel for the build-dependency


      - name: Install build tools (cache miss)
        if: steps.cache-wheel.outputs.cache-hit != 'true'
        run: |
          python -m pip install build

      - name: Build wheel for ${{ matrix.dependency.name }} (cache miss)
        if: steps.cache-wheel.outputs.cache-hit != 'true'
        run: |
          git clone --branch ${{ matrix.dependency.ref }} ${{ matrix.dependency.url }} ${{ matrix.dependency.name }}
          cd ${{ matrix.dependency.name }}
          python -m build --wheel
          mkdir -p  ~/.cache/cache-wheel/
          cp dist/*whl ~/.cache/cache-wheel/

      - name: Store wheel of ${{ matrix.dependency.name }} for use
        uses: actions/upload-artifact@v7
        with:
          name: build-dependency-${{ matrix.dependency.name }}-wheel
          path: |
           ~/.cache/cache-wheel/*.whl
          if-no-files-found: error

  build-sasview:
    needs: [build-dependencies]

    name: Build wheel sasview

    env:
      UV_SYSTEM_PYTHON: 1

    runs-on: ubuntu-latest

    steps:
      - name: Obtain SasView source from git
        uses: actions/checkout@v6
        with:
          fetch-depth: 0

      - name: Set up Python
        uses: actions/setup-python@v6
        with:
          python-version: ${{ env.RELEASE_PYVER }}

      - name: Install uv utilities to speed up python module installation
        uses: astral-sh/setup-uv@v7
        with:
          enable-cache: true
          prune-cache: false

      ### Installation of build-dependencies

      - name: Install system library build-dependencies
        env:
          DEBIAN_FRONTEND: noninteractive
        run: |
          echo "set man-db/auto-update false" | sudo debconf-communicate
          sudo dpkg-reconfigure man-db
          sudo eatmydata apt-get update
          # libcairo2-dev is for building a wheel for pycairo if not cached
          # rest are for loading Qt widgets
          sudo eatmydata apt-get -y install libxkbcommon-x11-0 libxcb-icccm4 libxcb-image0 libxcb-keysyms1 libxcb-randr0 libxcb-render-util0 libxcb-xinerama0 libxcb-xfixes0 x11-utils xvfb libegl-dev libcairo2-dev

      - name: Fetch wheels of sibling projects
        uses: actions/download-artifact@v8
        with:
          path: dist/
          pattern: build-dependency-*-wheel
          merge-multiple: true

      - name: Install correct versions of sibling projects
        run: |
          uv pip install dist/*whl

      - name: Install Python dependencies
        run: |
          uv pip install -r build_tools/requirements-dev.txt

      ### Actual building of sasview

      - name: Build sasview
        run: |
          python -m build --no-isolation --sdist --wheel

      - name: Publish sdist
        uses: actions/upload-artifact@v7
        with:
          name: sasview-sdist
          path: |
            dist/sasview*tar*
          if-no-files-found: error

      - name: Publish wheel package
        uses: actions/upload-artifact@v7
        with:
          name: sasview-wheel
          path: |
            dist/sasview*whl
          if-no-files-found: error

  test-matrix:
    needs: [matrix, build-sasview]

    strategy:
      fail-fast: false
      matrix:
        include: ${{ fromJson(needs.matrix.outputs.test-matrix-json) }}
    env:
      UV_SYSTEM_PYTHON: 1

    name: "${{ matrix.job_name }}"

    runs-on: ${{ matrix.os }}

    steps:
      - name: Obtain SasView source from git
        uses: actions/checkout@v6

      - name: Install sasview wheel (and dependencies)
        uses: ./.github/actions/install-wheel
        with:
          python-version: ${{ matrix.python-version }}
          os: ${{ matrix.os }}

      ### Run tests

      - name: Install test dependencies
        run: |
          uv pip install -r build_tools/requirements-test.txt

      - name: Test with pytest
        if: ${{ matrix.tests }}
        env:
          PYOPENCL_COMPILER_OUTPUT: 1
        run: |
          # run the tests against the installed package
          cp -r test pyproject.toml conftest.py $RUNNER_TEMP
          cd $RUNNER_TEMP
          python -m pytest -v -s test

      - name: Test GUI (Linux)
        if: ${{ matrix.os == 'ubuntu-latest' }}
        env:
          PYOPENCL_COMPILER_OUTPUT: 1
          QT_QPA_PLATFORM: offscreen
        run: |
          # Ensure all test running dependencies are installed (https://pytest-qt.readthedocs.io/en/latest/troubleshooting.html)
          sudo apt install -y libxkbcommon-x11-0 libxcb-icccm4 libxcb-image0 libxcb-keysyms1 libxcb-randr0 libxcb-render-util0 libxcb-xinerama0 libxcb-xfixes0 x11-utils
          /sbin/start-stop-daemon --start --quiet --pidfile /tmp/custom_xvfb_99.pid --make-pidfile --background --exec /usr/bin/Xvfb -- :99 -screen 0 1920x1200x24 -ac +extension GLX
          # Run the UI generation routine (with force recreate enabled)
          python src/sas/qtgui/convertUI.py -f
          # Suppress SIGSEGV from the tests until they can be fixed
          retval=0
          xvfb-run -a --server-args="-screen 0 1600x900x24" python -m pytest -rsx -v src/sas/qtgui/ || retval=$?
          if [ $retval -eq 139 ]; then echo "WARNING: Python interpreter exited with Segmentation Fault. This normally indicates that Qt objects were not correctly deleted. This error is currently suppressed in SasView's test suite."; retval=0; fi
          exit $retval

  installer-matrix:
    needs: [matrix, build-sasview]
    if: github.event_name != 'push' || github.ref_name == 'main' || startsWith(github.ref, 'refs/tags/')

    strategy:
      fail-fast: false
      matrix:
        include: ${{ fromJson(needs.matrix.outputs.installer-matrix-json) }}
    env:
      MACOS_DMG_NAME: SasView6-${{ matrix.os }}.dmg

      # Only sign the installer if non-forked repo and the build is important enough to sign
      SIGN_INSTALLER: ${{
        (
          (! github.event.repository.fork) &&
          (! github.event.pull_request.head.repo.fork) &&
          (startsWith(github.ref, 'refs/tags/v') ||
          startsWith(github.ref, 'refs/heads/release'))
        ) && 'true' || '' }}

      UV_SYSTEM_PYTHON: 1

    name: "${{ matrix.job_name }}"

    runs-on: ${{ matrix.os }}

    steps:
      - name: Obtain SasView source from git
        uses: actions/checkout@v6

      - name: Install sasview wheel (and dependencies)
        uses: ./.github/actions/install-wheel
        with:
          python-version: ${{ matrix.python-version }}
          os: ${{ matrix.os }}

      ### Build the installer

      - name: Install utilities to build installer
        if: ${{ matrix.installer }}
        run: |
          uv pip install pyinstaller

      - name: Generate the embedded credits file for all packages
        if: ${{ matrix.installer }}
        run: |
          uv pip install pip-licenses
          python build_tools/compile_licenses.py installers/credits.html

      - name: Build sasview with pyinstaller
        if: ${{ matrix.installer }}
        run: |
          cd installers
          rm -rf build/ dist/
          mkdir -p dist
          pyinstaller sasview.spec
          cd dist
          # the following builds a symlink farm in the package; it should
          # not be necessary, but without it, there will be lots of errors
          # about .so not found under linux.
          command -v ldconfig >/dev/null 2>&1 && ldconfig -n sasview
          tar zcf sasview-pyinstaller-dist.tar.gz sasview

      - name: Collect a debug tarball of the installer package
        if: ${{ matrix.installer }}
        uses: actions/upload-artifact@v7
        with:
          name: Debug-SasView-Installer-${{ matrix.os }}-${{ matrix.python-version }}
          path: |
            installers/dist/sasview-pyinstaller-dist.tar.gz
          if-no-files-found: warn

      - name: Install OS-specific installer tools (Windows)
        if: ${{ startsWith(matrix.os, 'windows') }}
        run: |
          choco install innosetup

      - name: Build sasview installer with INNO (Windows)
        if: ${{ startsWith(matrix.os, 'windows') }}
        run: |
          iscc installers/installer.iss
          mv installers/Output/setupSasView.exe installers/dist

      - name: Build sasview installer dmg file (OSX)
        if: ${{ startsWith(matrix.os, 'macos') }}
        run: |
          uv pip install dmgbuild
          installers/macos/create_dmg.sh "$MACOS_DMG_NAME"

      - name: Build sasview installer tarball (Linux)
        if: ${{ startsWith(matrix.os, 'ubuntu') }}
        run: |
          cd installers/dist
          tar zcf SasView6.tar.gz sasview

      - name: Sign executable and create dmg (OSX)
        if: ${{ startsWith(matrix.os, 'macos') && env.SIGN_INSTALLER }}
        env:
          MACOS_CERTIFICATE: ${{ secrets.MACOS_CERTIFICATE_ISA }}
          MACOS_CERTIFICATE_PWD: ${{ secrets.MACOS_CERTIFICATE_ISA_PWD }}
        run: |
          echo $MACOS_CERTIFICATE | base64 --decode > certificate.p12
          security create-keychain -p DloaAcYP build.keychain
          security default-keychain -s build.keychain
          security unlock-keychain -p DloaAcYP build.keychain
          security import certificate.p12 -k build.keychain -P $MACOS_CERTIFICATE_PWD -T /usr/bin/codesign
          security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k DloaAcYP build.keychain
          security find-identity -p codesigning

          cd installers/dist
          python ../../build_tools/fix_qt_folder_names_for_codesign.py SasView6.app
          python  ../../build_tools/code_sign_osx.py
          codesign --verify --options=runtime --entitlements ../../build_tools/entitlements.plist --timestamp --deep --verbose=4 --force --sign "Developer ID Application: The International Scattering Alliance (8CX8K63BQM)" SasView6.app
          uv pip install dmgbuild
          ../../installers/macos/create_dmg.sh "$MACOS_DMG_NAME"
          codesign -s "Developer ID Application: The International Scattering Alliance (8CX8K63BQM)" $MACOS_DMG_NAME

      - name: Notarize Release Build (OSX)
        if: ${{ startsWith(matrix.os, 'macos') && env.SIGN_INSTALLER }}
        uses: lando/notarize-action@v2
        with:
          product-path: installers/dist/SasView6-${{ matrix.os }}.dmg
          primary-bundle-id: "org.sasview.SasView6"
          appstore-connect-username: ${{ secrets.NOTARIZATION_USERNAME }}
          appstore-connect-password: ${{ secrets.NOTARIZATION_PASSWORD }}
          appstore-connect-team-id: 8CX8K63BQM
          verbose: True

      - name: Staple Release Build (OSX)
        if: ${{ startsWith(matrix.os, 'macos') && env.SIGN_INSTALLER }}
        uses: BoundfoxStudios/action-xcode-staple@v1
        with:
          product-path: installers/dist/SasView6-${{ matrix.os }}.dmg

      - name: Setup SM_CLIENT_CERT_FILE from base64 secret data
        if: ${{ startsWith(matrix.os, 'windows') && env.SIGN_INSTALLER }}
        run: |
          echo "${{ secrets.WINDOZE_CERT_DATA }}" | base64 --decode > /d/Certificate_pkcs12.p12
        shell: bash


      - name: Setup Software Trust Manager
        if: ${{ startsWith(matrix.os, 'windows') && env.SIGN_INSTALLER }}
        uses: digicert/code-signing-software-trust-action@v1
        with:
              simple-signing-mode: true
              # If the below 2 parameters are supplied, then smctl executable is invoked to attempt the signing.
              input: installers/dist/setupSasView.exe
              keypair-alias: ${{ secrets.KEYLOCKER_KEYPAIR_ALIAS }}
        env:
              SM_HOST: ${{ secrets.KEYLOCKER_HOST }}
              SM_API_KEY: ${{ secrets.KEYLOCKER_API_KEY }}
              SM_CLIENT_CERT_FILE: D:\\Certificate_pkcs12.p12
              SM_CLIENT_CERT_PASSWORD: ${{ secrets.WINDOZE_CERT_PASSWORD }}

      - name: Publish installer package
        uses: actions/upload-artifact@v7
        with:
          name: SasView-Installer-${{ matrix.os }}-${{ matrix.python-version }}
          path: |
            installers/dist/setupSasView.exe
            installers/dist/SasView6-macos-latest.dmg
            installers/dist/SasView6-macos-15-intel.dmg
            installers/dist/SasView6.tar.gz
          if-no-files-found: ignore


  test-installer:
    needs: [ matrix, installer-matrix ]
    if: github.event_name != 'push' || github.ref_name == 'main'

    strategy:
      fail-fast: false
      matrix:
        include: ${{ fromJson(needs.matrix.outputs.installer-matrix-json) }}

    name: "Test ${{ matrix.job_name }}"

    runs-on: ${{ matrix.os }}

    steps:
      - name: Set variables (Windows)
        if: ${{ startsWith(matrix.os, 'windows') }}
        run: |
          echo "INSTALL_PATH=$PWD/sasview/" >> $GITHUB_ENV
          echo "RUN_SASVIEW=$PWD/sasview/sasview.exe" >> $GITHUB_ENV

      - name: Set variables (Linux)
        if: ${{ startsWith(matrix.os, 'ubuntu') }}
        run: |
          echo "INSTALL_PATH=$PWD/sasview/" >> $GITHUB_ENV
          echo "RUN_SASVIEW=$PWD/sasview/sasview" >> $GITHUB_ENV

      - name: Set variables (Windows Powershell)
        if: ${{ startsWith(matrix.os, 'windows') }}
        shell: powershell
        # unfortunately we end up tripping over ourselves with paths
        # later on and need a PS version of the install path
        run: |
          "INSTALL_WIN_PATH=$(Get-Location)/sasview/" >> $env:GITHUB_ENV

      ### Obtain the installer, either from the previous step
      ### or from a previous run of the workflow

      - name: Retrieve installer (workflow image)
        if: ${{ env.INSTALLER_USE_OLD_IMAGE != 'true' }}
        uses: actions/download-artifact@v8
        id: download
        with:
          name: SasView-Installer-${{ matrix.os }}-${{ matrix.python-version }}

      - name: Set variables for download (workflow image)
        if: ${{ env.INSTALLER_USE_OLD_IMAGE != 'true' }}
        run: |
          echo "DL_PATH=${{steps.download.outputs.download-path}}" >> $GITHUB_ENV

      - name: Set variables for download (workflow image) (Windows)
        if: ${{ env.INSTALLER_USE_OLD_IMAGE != 'true' && startsWith(matrix.os, 'windows') }}
        shell: powershell
        run: |
          "DL_WIN_PATH=${{steps.download.outputs.download-path}}" >> $env:GITHUB_ENV

      - name: Retrieve installer (old image)
        if: ${{ env.INSTALLER_USE_OLD_IMAGE == 'true' }}
        id: download-old-installer
        uses: dawidd6/action-download-artifact@v21
        with:
          # Select a specific installer image based on the GitHub Actions run id
          run_id: ${{ env.INSTALLER_OLD_RUNID }}
          name: SasView-Installer-${{ matrix.os }}-${{ matrix.python-version }}
          path: downloads
          if_no_artifact_found: fail

      - name: Set variables for download (old image)
        if: ${{ env.INSTALLER_USE_OLD_IMAGE == 'true' }}
        run: |
          echo "DL_PATH=$PWD/downloads" >> $GITHUB_ENV

      - name: Set variables for download (old image) (Windows)
        if: ${{ env.INSTALLER_USE_OLD_IMAGE == 'true' && startsWith(matrix.os, 'windows') }}
        shell: powershell
        run: |
          "DL_WIN_PATH=$(Get-Location)/downloads" >> $env:GITHUB_ENV

      - name: Check downloads
        run: |
          echo "Sasview downloaded to: $DL_PATH"
          find "$DL_PATH"

      ### Run the installer and check that the installation looks OK

      - name: Run installer (Windows)
        if: ${{ startsWith(matrix.os, 'windows') }}
        # The installer spawns a new process and exits immediately, meaning
        # that the shell thinks it has finishes, tries to exit to move onto
        # the next step in the job, and kills the child process that is
        # trying to do the installation.
        # Wrapping the installer in "Start-Process ... -Wait" means that
        # this step doesn't exit until the installer has finished.
        shell: powershell
        run: |
          Start-Process -FilePath "${{ env.DL_WIN_PATH }}/setupSasView.exe" -ArgumentList "/SP- /VERYSILENT /SUPPRESSMSGBOXES /NORESTART /ALLUSERS /SKIPLICENSE=true /LANG=english /NOICONS /TASKS='' /LOG=${{ env.DL_WIN_PATH }}/install.log /DIR=${{ env.INSTALL_WIN_PATH }}" -Wait

      - name: Check installation log (Windows)
        if: ${{ startsWith(matrix.os, 'windows') }}
        run: |
          echo "Contents of installation log '$DL_PATH/install.log':"
          cat $DL_PATH/install.log

      - name: Run installer (Linux)
        if: ${{ startsWith(matrix.os, 'ubuntu') }}
        run: |
          # $INSTALL_PATH is already the base directory
          tar xf "$DL_PATH/SasView6.tar.gz"

      - name: Check installation files
        if: ${{ !startsWith(matrix.os, 'macos') }}
        run: |
          echo "File listing of SasView installed in '$INSTALL_PATH'"
          find "$INSTALL_PATH"

      - name: Try running the installation (Windows)
        if: ${{ startsWith(matrix.os, 'windows') }}
        # If sasview has crashed on its own, then this should return an error
        run: |
          $RUN_SASVIEW &
          sleep 60s
          kill %1

      - name: Install X11 libraries (Linux)
        if: ${{ startsWith(matrix.os, 'ubuntu') }}
        env:
          DEBIAN_FRONTEND: noninteractive
        run: |
          echo "set man-db/auto-update false" | sudo debconf-communicate
          sudo dpkg-reconfigure man-db
          sudo eatmydata apt-get update
          sudo eatmydata apt-get -y install --no-install-recommends libegl1 libopengl0 libxkbcommon-x11-0 libxcb-icccm4 libxcb-image0 libxcb-keysyms1 libxcb-randr0 libxcb-render-util0 libxcb-xinerama0 libxcb-xfixes0 x11-utils xvfb libxcb-cursor0

      - name: Try running the installation (Linux)
        if: ${{ startsWith(matrix.os, 'ubuntu' )}}
        # If sasview has crashed on its own, then this should return an error
        run: |
          (
            export https_proxy=https://127.0.0.1:9
            echo "## START SASVIEW"
            xvfb-run -a --server-args="-screen 0 1024x768x24" $RUN_SASVIEW 2>&1 |
            tee sasview-test.log
          ) &
          svpid=$!
          (
            set -e
            sleep 20s
            echo "## PULSE CHECK"
            kill -0 $svpid
            echo "## PULSE OK"
            sleep 40s
            echo "## FINISHING SMOKE TEST"
            kill $svpid
            echo "## SMOKE TEST COMPLETE"
            exit 0
          ) &
          pulsepid=$1
          wait $pulsepid
          # Check the log file for successful startup
          grep "SasView session started" sasview-test.log

      - name: Try running the installation (macOS)
        if: ${{ startsWith(matrix.os, 'macOS' )}}
        run: |
          hdiutil attach $DL_PATH/SasView6-${{ matrix.os }}.dmg
          # Testing scripting interface by running simple model generation through sasmodels compare
          /Volumes/SasView6/SasView6.app/Contents/MacOS/sasview -m sasmodels.compare cylinder -noplot

      ### Optionally attempt to work with the debug tarball from pyinstaller

      - name: Retrieve installer debug tarball
        if: ${{ env.INSTALLER_USE_DEBUG == 'true' }}
        id: download-old-debug
        uses: dawidd6/action-download-artifact@v21
        with:
          # Select a specific installer image based on the GitHub Actions run id
          run_id: ${{ env.INSTALLER_OLD_RUNID }}
          name: Debug-SasView-Installer-${{ matrix.os }}-${{ matrix.python-version }}
          path: downloads
          if_no_artifact_found: fail

      - name: Extract debug tarball
        if: ${{ env.INSTALLER_USE_DEBUG == 'true' }}
        run: |
          mkdir unpack
          cd unpack
          tar zxf ../downloads/sasview-pyinstaller-dist.tar.gz

      - name: Check debug installation files
        if: ${{ env.INSTALLER_USE_DEBUG == 'true' && startsWith(matrix.os, 'windows') }}
        run: |
          echo "File listing of SasView install bundle unpacked in 'unpack'"
          find unpack

      - name: Try running debug unpack
        if: ${{ env.INSTALLER_USE_DEBUG == 'true' && startsWith(matrix.os, 'windows') }}
        run: |
          cd unpack/sasview
          ./sasview.exe
