# Contributor: Andreas Radke <andyrtr@archlinux.org>
# Contributor: Tom Newsom <Jeepster@gmx.co.uk>

_pkgname=sqlite
pkgname=static-compat-$_pkgname
pkgver=3.50.4
_srcver=$(echo "$pkgver" | awk -F. '{ printf "%d%02d%02d00", $1, $2, $3 }')
pkgrel=1
pkgdesc="A C library that implements an SQL database engine"
arch=('x86_64')
license=('custom:Public Domain')
url="https://www.sqlite.org/"
depends=(static-compat-zlib static-compat-readline)
makedepends=(static-compat-configure static-compat-tcl patchelf)
source=(https://www.sqlite.org/2025/sqlite-src-${_srcver}.zip
        sqlite-lemon-system-template.patch
        license.txt)
options=('!emptydirs' 'staticlibs')
# upstream now switched to sha3sums - currently not suppoerted by makepkg
sha256sums=('b7b4dc060f36053902fb65b344bbbed592e64b2291a26ac06fe77eec097850e9'
            '55746d93b0df4b349c4aa4f09535746dac3530f9fd6de241c9f38e2c92e8ee97'
            '4e57d9ac979f1c9872e69799c2597eeef4c6ce7224f3ede0bf9dc8d217b1e65d')

prepare() {
  cd sqlite-src-$_srcver

  # Support system-wide template (located at /usr/share/lemon/lempar.c) in lemon.
  patch -Np1 -i ../sqlite-lemon-system-template.patch

  #autoreconf -vfi
}

build() {
  source static-compat-environment
  export PATH=$PWD:$PATH
  printf '#!/usr/bin/bash\nexec /usr/bin/pkg-config --static "$@"\n' > pkg-config
  chmod +x pkg-config

  # this uses malloc_usable_size, which is incompatible with fortification level 3
  export CFLAGS="${CFLAGS/_FORTIFY_SOURCE=3/_FORTIFY_SOURCE=2}"
  export CXXFLAGS="${CXXFLAGS/_FORTIFY_SOURCE=3/_FORTIFY_SOURCE=2}"

  export CPPFLAGS="$CPPFLAGS \
        -DSQLITE_ENABLE_COLUMN_METADATA=1 \
        -DSQLITE_ENABLE_UNLOCK_NOTIFY \
        -DSQLITE_ENABLE_DBSTAT_VTAB=1 \
        -DSQLITE_ENABLE_FTS3_PARENTHESIS \
        -DSQLITE_SECURE_DELETE \
        -DSQLITE_ENABLE_STMTVTAB \
        -DSQLITE_ENABLE_STAT4 \
        -DSQLITE_MAX_VARIABLE_NUMBER=250000 \
        -DSQLITE_MAX_EXPR_DEPTH=10000 \
        -DSQLITE_ENABLE_MATH_FUNCTIONS"

  # build sqlite
  cd sqlite-src-$_srcver
  static-compat-configure \
    --disable-shared \
    --enable-fts3 \
    --fts4 \
    --fts5 \
    --rtree \
  TCLLIBDIR="$static_compat_prefix"/lib/sqlite$pkgver
  make

  # build additional tools - broken build: changeset rbu
  make dbdump dbhash dbtotxt index_usage scrub showdb showjournal showshm \
       showstat4 showwal sqldiff sqlite3_analyzer sqlite3_checker \
       sqlite3_expert sqlite3_rsync sqltclsh
}

package() {
  source static-compat-environment
  cd sqlite-src-$_srcver
  make DESTDIR="${pkgdir}" install

  patchelf --remove-rpath "${pkgdir}/$static_compat_prefix"/bin/sqlite3
  install -D -m644 "${srcdir}"/license.txt "${pkgdir}"/usr/share/licenses/${pkgname}/license.txt
}
