name: CI-package-build

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

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

jobs:
  clean:
    runs-on: ubuntu-24.04
    outputs:
      gitdescribe: ${{ steps.gitdescribe.outputs.gitdescribe }}
    steps:
    
    - name: Git describe
      id: gitdescribe
      env:
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
      run: |
        VERS=$(gh api repos/${{ github.repository }}/git/refs/tags/${BRANCH#v} | jq -r '.[-1].ref' | sed -e 's|refs/tags/||g')
        HASH=$(gh api repos/${{ github.repository }}/git/refs/heads/${BRANCH} | jq -r '.object.sha' | cut -c-7)
        CMTS=$(gh api repos/${{ github.repository }}/compare/${VERS}...${BRANCH} | jq -r '.ahead_by')
        echo "GIT_VERSION=${VERS}-${CMTS}-g${HASH}" >> $GITHUB_ENV
        echo "gitdescribe=${VERS}-${CMTS}-g${HASH}" >> $GITHUB_OUTPUT
    
    - name: Clean packages
      env:
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
      run: |
        # gh release delete-asset ${BRANCH}-head
        gh release delete ${{ env.BRANCH }}-head --repo ${{ github.repository }} --cleanup-tag || true
        gh release create ${{ env.BRANCH }}-head --repo ${{ github.repository }} --title "${{ env.BRANCH }}-head - ${{ env.GIT_VERSION }}" --target ${{ env.SHA }} --draft --prerelease --notes-file - << EOF
        ## Development Snapshot
        
        GH-Action Package-Build on ${{ env.BRANCH }} merge
        
        Version : **${{ env.GIT_VERSION }}**
        
        Started : **$(date '+%Y-%m-%d %H:%M:%S %Z')**
        
        Status : **Build in progress**
        
        [![CI-Package-Build](https://github.com/${{ github.repository }}/actions/workflows/CI-package-build.yml/badge.svg)](https://github.com/${{ github.repository }}/actions/workflows/CI-package-build.yml)
        
        EOF
   
  select:
    runs-on: ubuntu-24.04
    outputs:
      dists: ${{ steps.select.outputs.dists }}
    steps:
    
    - name: Select distros
      id: select
      run: |
        set -x
        fn_get_targets () {
          # make -n amd64-packages | grep -i binaries/proxysql | wc -l
          # make -n arm64-packages | grep -i binaries/proxysql | wc -l
          # recursive get targets
          [[ -z ${MKFL} ]] && MKFL=$(curl -sL https://raw.githubusercontent.com/sysown/proxysql/${BRANCH}/Makefile)
          for TRG in ${@}; do
            local SUBTRG=$(echo "${MKFL}" | grep "${TRG}:")
            if [[ "${SUBTRG#*:}" =~ (arm64|amd64) ]]; then
              fn_get_targets ${SUBTRG#*:}
            else
              echo "${SUBTRG#*: }" | sed 's/ /\n/g'
            fi
          done
        }
        echo "dists=$(fn_get_targets amd64-packages | sed 's/-clang//g; s/-dbg//g' | sort | uniq | jq -Rcs 'split("\n") | .[:-1]')" >> $GITHUB_OUTPUT
        #echo "dists=$(fn_get_targets arm64-packages | sed 's/-clang//g; s/-dbg//g' | sort | uniq | jq -Rcs 'split("\n") | .[:-1]')" >> $GITHUB_OUTPUT
        #echo "dists=$(make pkglist | sed 's/proxysql[_0-9.-]*//g; s/[._].*//; s/dbg-//; s/-clang//' | sort | uniq | jq -Rcs 'split("\n") | .[:-1]')" >> $GITHUB_OUTPUT

  build:
    needs: [ clean, select ]
    strategy:
      fail-fast: false
      matrix:
#       # v2.7
#        dist: [ 'almalinux8','almalinux9','centos7','centos8','centos9','debian10','debian11','debian12','fedora38','fedora39','fedora40','fedora41','opensuse15','ubuntu16','ubuntu18','ubuntu20','ubuntu22','ubuntu24' ]
#       # v3.0
#        dist: [ 'almalinux8','almalinux9','centos9','debian12','fedora40','fedora41','opensuse15','ubuntu22','ubuntu24' ]
        arch: [ 'amd64','arm64' ]
        dist: ${{ fromJson(needs.select.outputs.dists) }}
        type: [ '','-dbg','-clang' ]
        exclude:
#         broken - clang too old
          - dist: 'centos7'
            type: '-clang'
          - dist: 'debian10'
            type: '-clang'
          - dist: 'ubuntu16'
            type: '-clang'
          - dist: 'ubuntu18'
            type: '-clang'
#         unneded - not build before v3.0.0
          - arch: 'arm64'
            type: '-clang'
          - arch: 'arm64'
            type: '-dbg'

    runs-on: ubuntu-24.04${{ matrix.arch == 'arm64' && '-arm' || '' }}
    env:
      ARCH: ${{ matrix.arch }}
      DIST: ${{ matrix.dist }}
      TYPE: ${{ matrix.type }}
      MATRIX: '(${{ matrix.arch }},${{ matrix.dist }},${{ matrix.type }})'

    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: Checkout repository
      uses: actions/checkout@v4
      with:
        repository: ${{ github.repository }}
        ref: ${{ env.SHA }}
        fetch-depth: 0
       
    - name: Build package
      run: |
        #[[ $(git describe --long --abbrev=7) == ${{ needs.clean.outputs.gitdescribe }} ]] || exit 1
        make ${{ matrix.dist }}${{ matrix.type }}
        echo "BIN_PKG=$(ls -1 binaries/*[mb])" >> $GITHUB_ENV
        echo "BIN_HASH=$(ls -1 binaries/*.id-hash)" >> $GITHUB_ENV

    - name: Push packages
      env:
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
      run: |
        GIT_VERSION=$(gh release --repo ${{ github.repository }} view ${{ env.BRANCH }}-head | tr -d '*' | grep -Po "(?<=Version : ).*")
        [[ ${GIT_VERSION} == ${{ needs.clean.outputs.gitdescribe }} ]] || exit 1
        gh release upload ${{ env.BRANCH }}-head --repo ${{ github.repository }} --clobber ${{ env.BIN_PKG }}
 
    - 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 }}'

  finalize:
    runs-on: ubuntu-24.04
    needs: [ clean, select, build ]
    steps:
    - name: Update release
      env:
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
      run: |
        GIT_VERSION=$(gh release --repo ${{ github.repository }} view ${{ env.BRANCH }}-head | tr -d '*' | grep -Po "(?<=Version : ).*")
        [[ ${GIT_VERSION} == ${{ needs.clean.outputs.gitdescribe }} ]] || exit 1
        gh release edit ${{ env.BRANCH }}-head --draft --prerelease --repo ${{ github.repository }} --tag ${{ env.BRANCH }}-head --notes-file - << EOF
        ## Development Snapshot
        
        GH-Action Package-Build on ${{ env.BRANCH }} merge
        
        Version : **${{ needs.clean.outputs.gitdescribe }}**
        
        Finished : **$(date '+%Y-%m-%d %H:%M:%S %Z')**
        
        Status : **Build is finished**
        
        [![CI-Package-Build](https://github.com/${{ github.repository }}/actions/workflows/CI-package-build.yml/badge.svg)](https://github.com/${{ github.repository }}/actions/workflows/CI-package-build.yml)
        
        EOF
        
        
