name: Build - AppImage

on:
  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 dependencies
        run: |
          sudo apt update
          sudo apt install libqcustomplot-dev libqscintilla2-qt5-dev libqt5svg5 libsqlcipher-dev libsqlite3-dev qttools5-dev

      - if: matrix.sqlcipher == 0
        name: Build SQLite
        run: |
          TARBALL=$(curl -s https://sqlite.org/download.html | awk '/<!--/,/-->/ {print}' | grep 'sqlite-autoconf' | cut -d ',' -f 3)
          SHA3=$(curl -s https://sqlite.org/download.html | awk '/<!--/,/-->/ {print}' | grep 'sqlite-autoconf' | cut -d ',' -f 5)
          curl -LsS -o sqlite.tar.gz https://sqlite.org/${TARBALL}
          VERIFY=$(openssl dgst -sha3-256 sqlite.tar.gz | cut -d ' ' -f 2)
          if [ "$SHA3" != "$VERIFY" ]; then exit 1 ; fi
          tar -xzf sqlite.tar.gz && cd sqlite-autoconf-*

          CPPFLAGS="-DSQLITE_ENABLE_COLUMN_METADATA=1 -DSQLITE_MAX_VARIABLE_NUMBER=250000 -DSQLITE_ENABLE_RTREE=1 -DSQLITE_ENABLE_GEOPOLY=1 -DSQLITE_ENABLE_FTS3=1 -DSQLITE_ENABLE_FTS3_PARENTHESIS=1 -DSQLITE_ENABLE_FTS5=1 -DSQLITE_ENABLE_STAT4=1 -DSQLITE_ENABLE_JSON1=1 -DSQLITE_SOUNDEX=1 -DSQLITE_ENABLE_MATH_FUNCTIONS=1 -DSQLITE_MAX_ATTACHED=125 -DSQLITE_ENABLE_MEMORY_MANAGEMENT=1 -DSQLITE_ENABLE_SNAPSHOT=1" ./configure --enable-shared=no
          make -j2 && sudo make install -j2

      - name: Configure build
        run: |
          mkdir appbuild && mkdir appdir && cd appbuild
          cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX:PATH=../appdir/usr -Wno-dev -DFORCE_INTERNAL_QSCINTILLA=ON -Dsqlcipher=${{ matrix.sqlcipher }} ..

      - name: Build
        working-directory: ./appbuild
        run: make install -j2

      - name: Build AppImage
        run: |
          wget -c -nv "https://github.com/probonopd/linuxdeployqt/releases/download/continuous/linuxdeployqt-continuous-x86_64.AppImage"
          chmod a+x linuxdeployqt-continuous-x86_64.AppImage
          export VERSION=$(printf "dev-`git -C . rev-parse --short HEAD`")
          ./linuxdeployqt-continuous-x86_64.AppImage appdir/usr/share/applications/*.desktop -appimage

      - name: Rename a file
        run: |
          for i in DB_Browser_for_SQLite*; do mv "$i" "${i//_/.}"; done
          if [ "${{ matrix.sqlcipher }}" = "1" ]; then
            export FILE=$(ls DB.Browser.for.SQLite*.AppImage)
            export FILE=${FILE/SQLite/SQLCipher}
            mv DB.Browser.for.SQLite*.AppImage $FILE
          fi

      - name: Upload artifacts
        uses: actions/upload-artifact@v4
        with:
          name: build-artifacts-${{ matrix.os }}-${{ matrix.sqlcipher }}
          path: DB.Browser.for.*.AppImage
          retention-days: 1
