name: Build - Ubuntu

on:
  release:
    types: [created]
  workflow_call:

jobs:
  build:
    name: ${{ matrix.os }} - SQLCipher ${{ matrix.sqlcipher }}
    runs-on: ${{ matrix.os }}
    strategy:
      fail-fast: false
      matrix:
        os: [ubuntu-20.04]
        sqlcipher: ["0", "1"]
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Install and cache dependencies
        uses: awalsh128/cache-apt-pkgs-action@v1.4.2
        with:
          packages: libqcustomplot-dev libqscintilla2-qt5-dev libqt5svg5 libsqlcipher-dev libsqlite3-dev qttools5-dev

      - name: Configure CMake
        run: |
          cmake -S . -B build -DCMAKE_BUILD_TYPE=Release \
            -DCMAKE_INSTALL_PREFIX=${PWD}/install \
            -DCPACK_PACKAGE_DIRECTORY=${PWD}/package \
            -DENABLE_TESTING=ON \
            -Dsqlcipher=${{ matrix.sqlcipher }}

      - name: Run make
        run: cmake --build build --config Release -j --target install

      - name: Run tests
        run: ctest -V -C Release --test-dir build

      - if: github.event_name == 'release'
        name: Package
        run: |
          cmake --build build --config Release -j --target package
          cmake -E remove_directory package/_CPack_Packages

      - if: github.event_name == 'release'
        name: Upload package
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          TAG: ${{ github.event.release.tag_name }}
          UPLOAD_URL: ${{ github.event.release.upload_url }}
        run: |
          set the env var TAG:
          $GITHUB_API_URL/repos/$GITHUB_REPOSITORY/releases/tags/$TAG | jq -r .upload_url)
          UPLOAD_URL=${UPLOAD_URL%\{*} # remove "{name,label}" suffix
          for pkg in package/*.*; do
            NAME=$(basename $pkg)
            MIME=$(file --mime-type $pkg|cut -d ' ' -f2)
            curl -X POST -H "Accept: application/vnd.github.v3+json" -H "Authorization: token $GITHUB_TOKEN" -H "Content-Type: $MIME" --data-binary @$pkg $UPLOAD_URL?name=$NAME
          done
