name: CI-taptests-groups

on:
  workflow_dispatch:
  workflow_call:
    inputs:
      trigger:
        type: string
      testgroup:
        type: string

env:
  SHA: ${{ inputs.trigger && fromJson(inputs.trigger).event.workflow_run.head_sha || github.sha }}

jobs:
  select:
    runs-on: ubuntu-22.04
    outputs:
      matrix: ${{ steps.set-matrix.outputs.matrix }}
    strategy:
      fail-fast: false
      matrix:
        testdist: [ 'ubuntu22-tap' ]
#        infradb: [ 'mysql57', 'mysql80', 'mysql81', 'mysql82', 'mariadb10', 'mariadb11' ]
        infradb: [ 'mysql57' ]
    env:
      TESTDIST: ${{ matrix.testdist }}
      INFRADB:  ${{ matrix.infradb }}
      BLDCACHE: ${{ inputs.trigger && fromJson(inputs.trigger).event.workflow_run.head_sha || github.sha }}_${{ matrix.testdist }}_matrix

    steps:

#    - name: Wait for cache
#      if: ${{ env.BRANCH != 'none' }}
#      env:
#        GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
#      run: |
#        echo "Wating for cache '${BLDCACHE}' ..."
#        sleep $(( $RANDOM / 1024 ))
#        PROBE="$(gh cache list --limit 300 --repo ${{ github.repository }} | grep -i ${BLDCACHE} || echo '')"
#        while [[ -z ${PROBE} ]]; do
#          echo "Wating for cache '${BLDCACHE}' ..."
#          sleep 30
#          PROBE="$(gh cache list --limit 300 --repo ${{ github.repository }} | grep -i ${BLDCACHE} || echo '')"
#        done
#        echo "Cache available '${BLDCACHE}'"

    - name: Cache restore
      id: cache-matrix
      uses: actions/cache/restore@v4
      with:
        key: ${{ env.BLDCACHE }}
        fail-on-cache-miss: true
        path: |
          proxysql/tap-matrix*

    - name: Set matrix
      id: set-matrix
      run: |
        #echo -n "[ " > proxysql/tap-matrix.json
        #echo -n "'multiple_prepared_statements-t', " >> proxysql/tap-matrix.json
        #echo -n "'test_sqlite3_.*-t', " >> proxysql/tap-matrix.json
        #echo -n "'test_ssl_.*-t', " >> proxysql/tap-matrix.json
        #echo -n "'set_testing.*-t', " >> proxysql/tap-matrix.json
        #echo -n " ]" >> proxysql/tap-matrix.json
        #echo "matrix=$(cat proxysql/tap-matrix.json)" >> $GITHUB_OUTPUT

        #MATRIX="[ "
        #for TM in proxysql/tap-matrix*.json; do
        #  TM=${TM#proxysql/tap-matrix-}
        #  MATRIX+="'${TM%.json}', "
        #done
        #MATRIX+=" ]"

        #MATRIX="[ 'tests', 'tests_with_deps/deprecate_eof_support' ]"
        MATRIX=$(cat proxysql/tap-matrix.json)
        echo "===================="
        echo "matrix=${MATRIX}"
        echo "===================="
        echo "matrix=${MATRIX}" >> $GITHUB_OUTPUT


  tests:
    runs-on: ubuntu-22.04
    needs: [ "select" ]
    strategy:
      fail-fast: false
      matrix:
        testdist: [ 'ubuntu22-tap' ]
#        infradb: [ 'mysql57', 'mysql80', 'mysql81', 'mysql82', 'mariadb10', 'mariadb11' ]
        infradb: [ 'mysql57' ]
#        testgroup: [ '.*admin.*-t|.*basic.*-t|.*charset.*-t|.*firewall.*-t|.*kill.*-t|.*max.*-t', 'multiple.*-t', '.*mysql.*-t', '.*prepare.*-t', 'reg_test.*-t', 'save.*-t', '.*set.*-t', '.*sqlite.*-t', '.*ssl.*-t', 'test_.*-t' ]
#        testgroup: [ '' ]
#        testgroup: [ 'kill_connection3-t', 'reg_test_3847_admin_lock-t', 'set_testing-240-t', 'max_connections_ff-t', 'test_server_sess_status-t' ]
        testgroup: ${{ fromJson(needs.select.outputs.matrix) }}
    env:
      TESTDIST: ${{ matrix.testdist }}
      INFRADB:  ${{ matrix.infradb }}
      TESTGROUP: ${{ matrix.testgroup }}
      BLDCACHE: ${{ inputs.trigger && fromJson(inputs.trigger).event.workflow_run.head_sha || github.sha }}_${{ matrix.testdist }}
      MATRIX: '(${{ matrix.testgroup }})'

    steps:

    - uses: LouisBrunner/checks-action@v2.0.0
      id: checks
      if: always()
      with:
        token: ${{ secrets.GITHUB_TOKEN }}
        name: '${{ github.workflow }} / ${{ github.job }} ${{ env.MATRIX }}'
        repo: ${{ github.repository }}
        sha: ${{ env.SHA }}
        status: 'in_progress'
#        action_url: 'https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}'
        details_url: 'https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}'
    
#    - name: Maximize build space
#      uses: easimon/maximize-build-space@master
#      with:
#        root-reserve-mb: 4096
#        swap-size-mb: 4096
##        remove-dotnet: 'true'

    - name: Install dependencies
      run: |
        sudo apt-get update -y
        sudo apt-get full-upgrade -y
        sudo apt-get install -y python3-pymysql python3-structlog sysbench mycli
        sudo pip3 install fastcov
        
        wget https://github.com/openark/orchestrator/releases/download/v3.2.6/orchestrator-client_3.2.6_amd64.deb
        sudo dpkg -i orchestrator-client_3.2.6_amd64.deb
        
        sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 467B942D3A79BD29
        wget https://repo.mysql.com/mysql-apt-config_0.8.29-1_all.deb
        sudo dpkg -i mysql-apt-config_0.8.29-1_all.deb
        # mysql-apt-config.postinst writes an expired signing key into the
        # keyring referenced by sources.list.d/mysql.list (signed-by=...).
        # Overwrite with the renewed key (same fingerprint, valid through
        # 2027-10-23) so apt-get update trusts the InRelease signature.
        wget -qO - https://repo.mysql.com/RPM-GPG-KEY-mysql-2025 | sudo gpg --dearmor --yes -o /usr/share/keyrings/mysql-apt-config.gpg
        sudo apt-get update -y
        sudo apt-cache policy mysql-shell
        sudo apt-get install -y mysql-shell

        sudo sed -i 's/8.0/5.7/' /etc/apt/sources.list.d/mysql.list
        sudo sed -i 's/jammy/bionic/' /etc/apt/sources.list.d/mysql.list
        sudo apt-get update -y
        sudo apt-cache policy libmysqlclient-dev
        sudo apt-get install -y --allow-downgrades libmysqlclient-dev=5.7*

    - name: Cache restore src
      id: cache-src
      uses: actions/cache/restore@v4
      with:
        key: ${{ env.BLDCACHE }}_src
        fail-on-cache-miss: true
        path: |
          proxysql/src/

    - name: Cache restore test
      id: cache-test
      uses: actions/cache/restore@v4
      with:
        key: ${{ env.BLDCACHE }}_test
        fail-on-cache-miss: true
        path: |
          proxysql/test/

    - name: Checkout jenkins_build_scripts
      uses: actions/checkout@v4
      with:
        repository: 'proxysql/jenkins-build-scripts'
        ref: 'master'
#        fetch-depth: 0
        path: 'jenkins-build-scripts'
        token: ${{ secrets.GH_TOKEN_PROXYSQL }}
        submodules: 'false'

    - name: Configure jenkins/
      run: |
        cd jenkins-build-scripts
        
        # configure paths
        sed -i "s|JENKINS_SCRIPTS_PATH=.*|JENKINS_SCRIPTS_PATH=${{ github.workspace }}/jenkins-build-scripts|" env.sh
        sed -i "s|WORKSPACE=.*|WORKSPACE=${{ github.workspace }}/proxysql|" env.sh

    - name: Configure proxysql/test
      run: |
        cd proxysql
        #mkdir test
        
        # select tests
        echo 'export TAP_WORKDIR="$WORKSPACE/test/tap/${{ matrix.testgroup }}/"' >> test/env.sh
        echo "export TEST_PY_INTERNAL=0" >> test/env.sh
        echo "export TEST_PY_BENCHMARK=0" >> test/env.sh
        echo "export TEST_PY_CHUSER=0" >> test/env.sh
        echo "export TEST_PY_STATS=0" >> test/env.sh
        echo "export TEST_PY_TAP=1" >> test/env.sh
        echo "export TEST_PY_TAPINT=0" >> test/env.sh
        echo "export TEST_PY_FAILOVER=0" >> test/env.sh
        echo 'export TEST_PY_TAP_INCL=""' >> test/env.sh
        echo 'export TEST_PY_TAP_EXCL=""' >> test/env.sh
        echo 'export MALLOC_CONF="retain:false"' >> test/env.sh
        echo 'export WITHGCOV=0' >> test/env.sh
        #echo 'export TAP_DISK_USAGE="$WORKSPACE/ci_*_logs/* $WORKSPACE/ci_infra_logs/regular_infra/proxysql $WORKSPACE/ci_tests_logs/proxysql-tester.py/* $WORKSPACE/src /home/runner/runners/*"' >> test/env.sh
        #echo 'export' >> test/env.sh
        #cat test/env.sh

        # remove incompatible tests
        set +e
        #cd ${{ github.workspace }}/proxysql/test/tap/$TAPGROUP
        cd ${{ github.workspace }}/proxysql/test/tap/tests
        # broken
        rm -f reg_test_3273_ssl_con-t
        rm -f test_flush_logs-t
        # missing infra
        rm -f clickhouse_php_conn-t
        rm -f reg_test_3603-stmt_metadata-t
        rm -f reg_test_3992_fast_forward_malformed_packet-mysqlsh-t
        rm -f reg_test_3992_fast_forward_malformed_packet-pymysql-t
        rm -f reg_test_3992_fast_forward_malformed_packet-t
        rm -f reg_test_fast_forward_split_packet-t
        rm -f set_testing-240-t
        rm -f test_binlog_reader-t
        #rm -f test_binlog_reader_uses_previous_hostgroup-t
        #rm -f test_binlog_fast_forward-t
        rm -f test_clickhouse_server-t
        rm -f test_clickhouse_server_libmysql-t
        rm -f test_cluster1-t
        rm -f test_cluster_sync-t
        rm -f test_com_reset_connection_com_change_user-t
        rm -f test_log_last_insert_id-t
        rm -f test_read_only_actions_offline_hard_servers-t
        rm -f test_rw_binary_data-t
        rm -f test_server_sess_status-t
        rm -f test_session_status_flags-t
        rm -f test_auth_methods-t
        rm -f test_sqlite3_pass_exts-t
        # missing cluster
        rm -f reg_test_3765_ssl_pollout-t
        rm -f reg_test__ssl_client_busy_wait-t
        rm -f test_unshun_algorithm-t

        # FAIL
        #rm -f test_mysql_connect_retries-t

        # fixes
        sed -i '/TAP_MYSQLPORT/d' ${{ github.workspace }}/proxysql/test/tap/tests/reg_test_4556-ssl_error_queue-t.env
        cd ${{ github.workspace }}/proxysql/test/tap/tests
        ls -al
        
        true

    - name: Run proxysql
      run: |
        #set -x
        set +e
        cd ${{ github.workspace }}/jenkins-build-scripts
        source ./env.sh
        
        #./cluster_start.bash
        #sleep 10
        
        cd ${{ github.workspace }}/proxysql
        mkdir -p ci_infra_logs/regular_infra/proxysql
        cd src
        mkdir coverage_reports

        (./proxysql --clickhouse-server --sqlite3-server --idle-threads -f -c "$DOCKER_SCRIPT_PATH/conf/proxysql/proxysql.cnf" -D $REGULAR_INFRA_DATADIR &> $REGULAR_INFRA_DATADIR/proxysql.log) &
        sleep 10
        mysql -uadmin -padmin -h127.0.0.1 -P6032 -e "SELECT version();" 2>&1 | grep -v "Using a password"
        
        cd ${{ github.workspace }}/jenkins-build-scripts
        ./cluster_init.bash
        sleep 10        

    - name: Infra
      run: |
        cd ${{ github.workspace }}/jenkins-build-scripts
        source ./env.sh
        
        cd ${{ github.workspace }}/jenkins-build-scripts/infra-docker-hoster
        sed -i 's|image: .*|image: ghcr.io/mrmohebi/docker-hoster|' docker-compose.yml
        ./docker-compose-init.bash

        cd ${{ github.workspace }}/jenkins-build-scripts/infra-mysql57
        sed -i "s/\${INFRA}-\${CONTAINER}-1/\${INFRA}_\${CONTAINER}_1/" docker-compose-init.bash
        ./docker-compose-init.bash

        VERS=$(mysql -uadmin -padmin -h127.0.0.1 -P6032 -e "SELECT version() \G;" | grep version |  awk '{ print $2 }')
        if [[ $VERS =~ ^3\. ]]; then
          cd ${{ github.workspace }}/jenkins-build-scripts/docker-pgsql16-single
          sed -i "s/\${INFRA}-\${CONTAINER}-1/\${INFRA}_\${CONTAINER}_1/" docker-compose-init.bash
          ./docker-compose-init.bash
        fi
        
        docker ps -a
        cat /etc/hosts

    - name: TAP-tests
      run: |
        set +e        
        cd ${{ github.workspace }}/jenkins-build-scripts
        source ./env.sh
        
        sudo -E ./test-scripts/bin/proxysql-tester.py
        RC=$?

        SUMMARY="$(grep -Po "SUMMARY: .*" ${{ github.workspace }}/proxysql/ci_tests_logs/proxysql-tester.log)"
        echo "$SUMMARY" >> $GITHUB_STEP_SUMMARY
        
        exit $RC

    - name: Cleanup
#      if: ${{ failure() && !cancelled() }}
      if: ${{ failure() || cancelled() }}
      run: |
        set +e
        cd ${{ github.workspace }}/jenkins-build-scripts
        source ./env.sh
        
        mysql -h127.0.0.1 -P6032 -uadmin -padmin -e "PROXYSQL SHUTDOWN SLOW" &> /dev/null
        sleep 10
        killall proxysql
        
        cd ${{ github.workspace }}/jenkins-build-scripts/infra-docker-hoster
        sed -i 's|image: .*|image: ghcr.io/mrmohebi/docker-hoster|' docker-compose.yml
        ./docker-compose-destroy.bash
        
        cd ${{ github.workspace }}/jenkins-build-scripts/infra-mysql57
        sed -i "s/\${INFRA}-\${CONTAINER}-1/\${INFRA}_\${CONTAINER}_1/" docker-compose-init.bash
        ./docker-compose-destroy.bash
        
        cd ${{ github.workspace }}/jenkins-build-scripts/docker-pgsql16-single
        sed -i "s/\${INFRA}-\${CONTAINER}-1/\${INFRA}_\${CONTAINER}_1/" docker-compose-init.bash
        ./docker-compose-destroy.bash
        
        sudo chmod -R 777 ${{ github.workspace }}/*
        echo "${{ matrix.testgroup }}" | tr -d '*|' | sed 's|.*/||' | xargs -0 printf 'TESTGROUP=%s' >> $GITHUB_ENV
          
    # Security note: this step runs a static chmod command against a path
    # under proxysql/; no untrusted user input is interpolated. The chmod
    # target is a fixed literal, the only variable substitution is inside
    # an if: expression that uses workflow-run state (failure/cancelled),
    # not event body fields.
    - name: Fix artifact permissions
      if: ${{ failure() || cancelled() }}
      run: |
        # actions/upload-artifact dies with EACCES when it scandirs into
        # directories under ci_*_logs/ that were created inside docker
        # build containers (root-owned). Make everything readable by the
        # runner user before upload. sudo required because files are
        # root-owned; 2>/dev/null + || true because the path may not
        # exist on all failure paths (e.g. a cache-restore failure before
        # any test even runs).
        sudo chmod -R a+rX proxysql/ci_*_logs/ 2>/dev/null || true

    - name: Archive artifacts logs
#      if: ${{ failure() && !cancelled() }}
      if: ${{ failure() || cancelled() }}
      uses: actions/upload-artifact@v4
      with:
        name: ${{ github.workflow }}-${{ env.SHA }}-logs-run#${{ github.run_number }}-${{ env.TESTGROUP }}
        path: |
          proxysql/ci_*_logs/

    - name: Archive artifacts bins
#      if: ${{ failure() && !cancelled() }}
      if: ${{ failure() || cancelled() }}
      uses: actions/upload-artifact@v4
      with:
        name: ${{ github.workflow }}-${{ env.SHA }}-bins-run#${{ github.run_number }}-${{ env.TESTGROUP }}
        path: |
          proxysql/binaries/
          proxysql/src/
          proxysql/libs/
#          proxysql/deps/

    - name: Archive artifacts tests
#      if: ${{ failure() && !cancelled() }}
      if: ${{ failure() || cancelled() }}
      uses: actions/upload-artifact@v4
      with:
        name: ${{ github.workflow }}-${{ env.SHA }}-tests-run#${{ github.run_number }}-${{ env.TESTGROUP }}
        path: |
          proxysql/test/tap/tests*
    
    - uses: LouisBrunner/checks-action@v2.0.0
      if: always()
      with:
        token: ${{ secrets.GITHUB_TOKEN }}
        check_id: ${{ steps.checks.outputs.check_id }}
        repo: ${{ github.repository }}
        sha: ${{ env.SHA }}
        conclusion: ${{ job.status }}
#        action_url: 'https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}'
        details_url: 'https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}'
