# Created by migrate-autoconf - fix items marked XXX
global autosetup
use cc cc-db cc-shared cc-lib hwaci-common
set DUMP_DEFINES_FILE defines.list
set enable_shared 1

# Are we cross compiling?
set cross_compiling 0
if {[get-define host] ne [get-define build]} {
  set cross_compiling 1
}
define cross_compiling ${cross_compiling}

########################################################################
# A very long story made short, autosetup's --flag handling has
# some behaviors which make it impossible to implement 100% identical
# flags, compared to the historical autotools build. The differences
# are documented here:
#
#
# 1) --debug is used by autosetup itself, so we have to rename it to
# --with-debug. We cannot use --enable-debug because that is, for
# autosetup, and alias for --debug=1.
#
# 2) In autosetup, all flags starting with (--enable, --disable) are
# forced to be booleans and received special handling in how they're
# resolved. Because of that we have to rename:
#
#   2.1) --enable-tempstore[=no] to --with-tempstore[=no].
#
options {
  with-debug:=1        => {Enable debug build flags}
  with-tclsh:          => {Full pathname of tclsh to use}
  with-tcl:            => {Directory containing tclConfig.sh}
  tcl=1                => {Disable building accessory programs that require TCL-dev}
  test-status          => {Enable status of tests}
  threadsafe=1         => {Disable mutexing}
  releasemode          => {libtool link to release mode}
  with-tempstore:=no => {Use an in-ram database for temporary tables: never,no,yes,always.}
  editline=0           => {BSD editline support}
  readline=1           => {Disable readline support}
  largefile=1          => {Disable large file support}
  with-readline-lib    => {readline library}
  with-readline-inc    => {readline include paths}
  with-linenoise:DIR   => {}
  amalgamation=1       => {Disable the amalgamation and instead build all files separately}
  load-extension=1     => {Disable loading of external extensions}
  math=1               => {Disable math functions}
  json=1               => {Disable JSON functions}
  all                  => {Enable FTS4, FTS5, Geopoly, RTree, Sessions}
  memsys5              => {Enable MEMSYS5}
  memsys3              => {Enable MEMSYS3}
  fts3                 => {Enable the FTS3 extension}
  fts4                 => {Enable the FTS4 extension}
  fts5                 => {Enable the FTS5 extension}
  update-limit         => {Enable the UPDATE/DELETE LIMIT clause}
  geopoly              => {Enable the GEOPOLY extension}
  rtree                => {Enable the RTREE extension}
  session              => {Enable the SESSION extension}
  gcov=0               => {Enable coverage testing using gcov}
  linemacros           => {Enable #line macros in the amalgamation.}
  with-wasi-sdk:=/opt/wasi-sdk
                       => {Top-most dir of the wasi-sdk for a WASI build.}
  with-emsdk:DIR       => {Top-most dir of the Emscripten SDK installation}
  dump-defines=1       => {Disable dump of autosetup defines to $DUMP_DEFINES_FILE}
}

set srcdir $autosetup(srcdir)
set top_srcdir [get-define abs_top_srcdir]
puts "srcdir = $srcdir"
puts "top_srcdir = $top_srcdir"
set RELEASE [readfile $autosetup(srcdir)/VERSION]
regsub {([0-9]*\.*[0-9]*).*} $RELEASE {\1} VERSION
define VERSION $VERSION
define RELEASE $RELEASE
puts "RELEASE = $RELEASE"
puts "VERSION = $VERSION"

define SQLITE_AUTOREMAKE cd
define-append SQLITE_AUTOREMAKE $autosetup(srcdir) && $top_srcdir/configure {*}$autosetup(argv)

set outOfTreeBuild 0
if {![file exists sqlite3.pc.in]} {
  puts "This appears to be an out-of-tree build."
  set outOfTreeBuild 1
}

cc-check-tools ld ar

# The build process allows for using a cross-compiler.  But the default
# action is to target the same platform that we are running on.  The
# configure script needs to discover the following properties of the
# build and target systems:
#
#    srcdir
#
#        The is the name of the directory that contains the
#        "configure" shell script.  All source files are
#        located relative to this directory.
#
#    bindir
#
#        The name of the directory where executables should be
#        written by the "install" target of the makefile.
#
#    program_prefix
#
#        Add this prefix to the names of all executables that run
#        on the target machine.  Default: ""
#
#    ENABLE_SHARED
#
#        True if shared libraries should be generated.
#
#    BUILD_CC
#
#        The name of a command that is used to convert C
#        source files into executables that run on the build
#        platform.
#
#    BUILD_CFLAGS
#
#        Switches that the build compiler needs in order to construct
#        command-line programs.
#
#    BUILD_LIBS
#
#        Libraries that the build compiler needs in order to construct
#        command-line programs.
#
#    TCL_*
#
#        Lots of values are read in from the tclConfig.sh script,
#        if that script is available.  This values are used for
#        constructing and installing the TCL extension.
#
#    TARGET_READLINE_LIBS
#
#        This is the library directives passed to the target linker
#        that cause the executable to link against the readline library.
#        This might be a switch like "-lreadline" or pathnames of library
#        file like "../../src/libreadline.a".
#
#    TARGET_READLINE_INC
#
#        This variables define the directory that contain header
#        files for the readline library.  If the compiler is able
#        to find <readline.h> on its own, then this can be blank.

########################################################################
# OPT_FEATURE_FLAGS = -DSQLITE_OMIT/ENABLE flags.
define OPT_FEATURE_FLAGS {}
define OPT_SHELL {}; # CFLAGS for the sqlite3 CLI app
# Adds $flag, if not empty, to OPT_FEATURE_FLAGS.
proc add-feature-flag {args} {
  if {"" ne $args} {
    define-append OPT_FEATURE_FLAGS {*}$args
  }
}
# add-feature-flag -DSQLITE_JUST_TESTING=3
proc add-shell-opt {args} {
  if {"" ne $args} {
    define-append OPT_SHELL {*}$args
  }
}

hwaci-check-exeext
if {".exe" eq [get-define TARGET_EXEEXT]} {
  define SQLITE_OS_UNIX 0
  define SQLITE_OS_WIN 1
  # todo? add -DSQLITE_OS_WIN=1 to CFLAGS?
} else {
  define SQLITE_OS_UNIX 1
  define SQLITE_OS_WIN 0
  # todo? add -DSQLITE_OS_UNIX=1 to CFLAGS?
}
define BDLL [hwaci-dll-extension build]
define TDLL [hwaci-dll-extension host]

#########
# Programs needed
if {"" eq [hwaci-bin-define install]} {
  msg-result "Cannot find install binary, so 'make install' will not work."
}

########################################################################
# Locate a compiler for the build machine.  This compiler should
# generate command-line programs that run on the build machine.
#
# XXX if test x"$cross_compiling" = xno; then
# XXX BUILD_CC=$CC
# XXX BUILD_CFLAGS=$CFLAGS
# XXX else
# XXX if test "${BUILD_CC+set}" != set; then
# XXX AC_CHECK_PROGS BUILD_CC gcc cc cl
# XXX fi
# XXX if test "${BUILD_CFLAGS+set}" != set; then
# XXX BUILD_CFLAGS="-g"
# XXX fi
# XXX fi
# XXX AC_SUBST BUILD_CC

define BUILD_CC [get-define CC_FOR_BUILD]
define BUILD_CFLAGS [get-env CFLAGS {-g}]

########################################################################
# Handle --with-wasi-sdk=DIR
#
# This must be early because it may change the toolchain and several
# config options.
#
# It's unclear whether we can actually get away with making these
# changes to the autosetup environment.
if {1} {
  set wasiSdkDir [opt-val with-wasi-sdk] ; # ??? [lindex [opt-val with-wasi-sdk] end]
  #puts "x wasiSdkDir=$wasiSdkDir foo=[lindex [opt-val with-wasi-sdk] end]"
  if {$wasiSdkDir ne ""} {
    msg-checking "Checking WASI SDK directory \[$wasiSdkDir]... "
    puts "prefix = [prefix $wasiSdkDir/bin {clang ld}]"
    hwaci-affirm-files-exist -v {*}[prefix "$wasiSdkDir/bin/" {clang wasm-ld}]
    msg-result "Using wasi-sdk clang, disabling: tcl, CLI shell, DLL, loadable extensions, threading"
    define HAVE_WASI_SDK 1
    define WASI_SDK_DIR $wasiSdkDir
    hwaci-opt-set load-extension 0; # ==> --disable-load-extension
    hwaci-opt-set threadsafe 0; # ==> --threadsafe
    hwaci-opt-set tcl 0; # ==> --disable-tcl
    define HAVE_TCL 0
    set cross_compiling 1
    # libtool is apparently hard-coded to use gcc for linking DLLs, so
    # we disable the DLL build.
    set enable_shared 0

    # Changing --host and --target have no effect here except to possibly
    # cause confusion. autoconf has finished processing them by this
    # point.
    #
    #  host_alias=wasm32-wasi
    #  target=wasm32-wasi
    #
    # Merely changing CC and LD to the wasi-sdk's is enough to get
    # sqlite3.o building in WASM format.
    # XXX CC="${wasiSdkDir}/bin/clang"
    # XXX LD="${wasiSdkDir}/bin/wasm-ld"
    # XXX RANLIB="${wasiSdkDir}/bin/llvm-ranlib"
    define CC "${wasiSdkDir}/bin/clang"
    define LD "${wasiSdkDir}/bin/wasm-ld"
    #define STRIP "${wasiSdkDir}/bin/strip"
  }
  unset wasiSdkDir
}; # --wasi-sdk-dir

########################################################################
# Check which TCL to use as a code generator
define CFLAGS_JIMSH {}
puts "Looking for path-resolution function for JimTCL... "
define BTCL "\$(JIMSH)"
if {[cc-check-functions realpath]} {
  define-append CFLAGS_JIMSH -DHAVE_REALPATH
} elseif {[cc-check-functions _fullpath]} {
  # _fullpath() is a Windows API
  define-append CFLAGS_JIMSH -DHAVE__FULLPATH
} else {
  puts "Cannot find realpath() or _fullpath(). Falling back to system's TCL for code generation."
}

########################################################################
# Enable large file support (if special flags are necessary)
cc-check-lfs

########################################################################
# Check for needed/wanted data types
cc-check-types int8_t int16_t int32_t int64_t intptr_t \
  uint8_t uint16_t uint32_t uint64_t uintptr_t

########################################################################
# Check for needed/wanted functions
cc-check-functions gmtime_r isnan localtime_r localtime_s \
  malloc_usable_size strchrnul usleep utime pread pread64 pwrite pwrite64

cc-check-function-in-lib fdatasync rt
define LDFLAGS_FDATASYNC [get-define lib_fdatasync]
undefine lib_fdatasync

########################################################################
# Check for needed/wanted headers
cc-check-includes \
  sys/types.h sys/stat.h dlfcn.h unistd.h \
  stdlib.h malloc.h memory.h \
  string.h strings.h \
  stdint.h inttypes.h

# These are optional for JimTCL:
cc-check-includes dirent.h sys/time.h

if {[cc-check-includes zlib.h] && [cc-check-function-in-lib deflate z]} {
  # TODO: port over the more sophisticated zlib search from the fossil auto.def
  define HAVE_ZLIB 1; # "-DSQLITE_HAVE_ZLIB=1"
  define LDFLAGS_ZLIB -lz
} else {
  define HAVE_ZLIB 0
  define LDFLAGS_ZLIB ""
}

hwaci-define-if-opt-truthy amalgamation USE_AMALGAMATION \
  "Use amalgamation for builds?"

hwaci-define-if-opt-truthy gcov USE_GCOV "Use gcov?"

hwaci-define-if-opt-truthy test-status TSTRNNR_OPTS \
  "test-runner flags:" {--status} {}

hwaci-define-if-opt-truthy linemacros AMALGAMATION_LINE_MACROS \
  "Use #line macros in the amalgamation:" {--linemacros=1} {--linemacros=0}

msg-checking "Debug build? "

hwaci-if-opt-truthy with-debug {
  define SQLITE_DEBUG 1
  define TARGET_DEBUG {-DSQLITE_DEBUG=1 -DSQLITE_ENABLE_SELECTTRACE -DSQLITE_ENABLE_WHERETRACE -O0 -Wall}
  msg-result yes
} {
  define TARGET_DEBUG {-DNDEBUG}
  msg-result no
}

hwaci-check-rpath

########################################################################
# TCL...
define HAVE_TCL 0
define TCLSH_CMD {exit 1}
if {"" eq [get-define CFLAGS_JIMSH]} {
  # We can't use JimTCL for in-tree generation on this system, so...
  #
  # Temporary solution for finding "a" tclsh. TODO is port the
  # full-featured check which lives in the elseif part of this block.
  set tclsh [hwaci-first-bin-of tclsh8.6 tclsh tclsh9.0]
  if {"" eq $tclsh} {
    user-error "Cannot find tclsh, which is required to build certain files."
  }
  define TCLSH_CMD $tclsh
  define BTCL $tclsh
  define HAVE_TCL 0 ; # until the following elseif block is ported
} elseif {0} {
  # Porting this section of configure.ac is going to be a bit of a slog...
  set tEnable [hwaci-opt-truthy tcl]
  set use_tcl $tEnable
  set tclsh ""
  #set original_use_tcl ${use_tcl}
  #########
  # Figure out all the name of a working tclsh and parameters needed to compile against Tcl.
  # The --with-tcl= and/or --with-tclsh= configuration arguments might be useful for this.
  #
  # XXX AC_ARG_WITH tclsh AS_HELP_STRING([--with-tclsh=PATHNAME],[full pathname of a tclsh to use])
  # XXX AC_ARG_WITH tcl AS_HELP_STRING([--with-tcl=DIR],[directory containing (tclConfig.sh)])
  set with_tclsh [opt-val with-tclsh]
  set with_tcl [opt-val with-tcl]

  if {"" eq $with_tclsh && "" eq $with_tcl} {
    # XXX if test x"${with_tclsh}" == x -a x"${with_tcl}" == x; then
    # XXX AC_CHECK_PROGS TCLSH_CMD tclsh8.6 tclsh tclsh9.0 none
    #set with_tclsh ${TCLSH_CMD}
    # XXX fi
    set with_tclsh [hwaci-first-bin-of tclsh8.6 tclsh tclsh9.0]
  }

  if {"" ne $with_tclsh } {
    # XXX if test x"${with_tclsh}" != x -a x"${with_tclsh}" != xnone; then
    # XXX TCLSH_CMD=${with_tclsh}
    set tclsh $with_tclsh
    puts "using tclsh at \"$tclsh\""
    if {$use_tcl} {
      # XXX if test x"${use_tcl}" = "xyes"; then
      #set with_tcl `${with_tclsh} <${srcdir}/tool/find_tclconfig.tcl`
      # XXX if test x"${with_tcl}" != x; then
      #msg-result "$TCLSH_CMD recommends the tclConfig.sh at ${with_tcl}"
      # XXX else
      #msg-result Warning: "$TCLSH_CMD is unable to recommend a tclConfig.sh"
      #set use_tcl no
      # XXX fi
      # XXX fi
    }
    # XXX fi
  }

  # XXX if test x"${use_tcl}" = "xyes"; then
  # XXX if test x"${with_tcl}" != x; then
  # XXX if test -r ${with_tcl}/tclConfig.sh; then
  # set tclconfig "${with_tcl}/tclConfig.sh"
  # XXX else
  # XXX for i in tcl8.6 tcl9.0 lib; do
  # XXX if test -r ${with_tcl}/$i/tclConfig.sh; then
  #set tclconfig ${with_tcl}/$i/tclConfig.sh
  # XXX break
  # XXX fi
  # XXX done
  # XXX fi
  # XXX if test ! -r "${tclconfig}"; then
  #user-error "no tclConfig.sh file found under ${with_tcl}"
  # XXX fi
  # XXX else
  # If we have not yet found a tclConfig.sh file, look in $libdir whic is
  # set automatically by autoconf or by the --prefix command-line option.
  # See https://sqlite.org/forum/forumpost/e04e693439a22457
  #set libdir ${prefix}/lib
  # XXX if test -r ${libdir}/tclConfig.sh; then
  #set tclconfig ${libdir}/tclConfig.sh
  # XXX else
  # XXX for i in tcl8.6 tcl9.0 lib; do
  # XXX if test -r ${libdir}/$i/tclConfig.sh; then
  #set tclconfig ${libdir}/$i/tclConfig.sh
  # XXX break
  # XXX fi
  # XXX done
  # XXX fi
  # XXX if test ! -r "${tclconfig}"; then
  #user-error "cannot find a usable tclConfig.sh file.
  #        Use --with-tcl=DIR to specify a directory where tclConfig.sh can be found.
  #        SQLite does not use TCL internally, but TCL is required to build SQLite
  #        from canonical sources and TCL is required for testing."
  # XXX fi
  # XXX fi
  # msg-result "loading TCL configuration from ${tclconfig}"
  # XXX . ${tclconfig}
  # XXX autosetup automatically substitutes all define'd values
  #     In general, simply 'define' the value rather than using a shell
  #     variable and AC_SUBST.
  #
  # XXX AC_SUBST TCL_INCLUDE_SPEC
  # XXX AC_SUBST TCL_LIB_SPEC
  # XXX AC_SUBST TCL_STUB_LIB_SPEC
  # There are lots of other configuration variables that are provided by the
  # tclConfig.sh file and that could be included here.  But as of right now,
  # TCL_LIB_SPEC is the only what that the Makefile uses.
  # XXX HAVE_TCL=1
  # XXX elif test x"${original_use_tcl}" = "xno"; then
  # msg-result "unable to run tests because of --disable-tcl"
  # XXX HAVE_TCL=0
  # XXX else
  # msg-result "unable to run tests because no tclConfig.sh file could be located"
  # XXX HAVE_TCL=0
  # XXX fi
  # XXX AC_SUBST HAVE_TCL
  # XXX if test x"$TCLSH_CMD" == x; then
  # XXX TCLSH_CMD=${TCL_EXEC_PREFIX}/bin/tclsh${TCL_VERSION}
  # XXX if test ! -x ${TCLSH_CMD}; then
  # set _2 ${TCL_EXEC_PREFIX}/bin/tclsh
  # XXX if test ! -x ${TCLSH_CMD_2}; then
  # msg-result Warning: "cannot find a usable tclsh at either ${TCLSH_CMD} or ${TCLSH_CMD_2}"
  # XXX TCLSH_CMD=none
  # XXX else
  # XXX TCLSH_CMD=${TCLSH_CMD_2}
  # XXX fi
  # XXX fi
  # XXX fi
  # XXX if test "$TCLSH_CMD" = "none"; then
  # If we can't find a local tclsh, then building the amalgamation will fail.
  # We act as though --disable-amalgamation has been used.
  # msg-result Warning: "Warning: can't find tclsh - defaulting to non-amalgamation build."
  # XXX USE_AMALGAMATION=0
  # XXX TCLSH_CMD="tclsh"
  # XXX fi
  # XXX AC_SUBST TCLSH_CMD

  # XXX AC_ARG_VAR TCLLIBDIR Where to install tcl plugin
  # XXX if test "x${TCLLIBDIR+set}" != "xset" ; then
  # XXX for i in `echo 'puts stdout $auto_path' | ${TCLSH_CMD}` ; do
  # XXX if test -d $i ; then
  # XXX TCLLIBDIR=$i
  # XXX break
  # XXX fi
  # XXX done
  # XXX TCLLIBDIR="${TCLLIBDIR}/sqlite3"
  # XXX fi

  unset tEnable with_tclsh with_tcl
}; # end of tcl


########################################################################
# Thread safety?
msg-checking "Support threadsafe operation? "
hwaci-if-opt-truthy threadsafe {
  msg-result yes
  add-feature-flag -DSQLITE_THREADSAFE=1
  if {![cc-check-function-in-lib pthread_create pthread]
      || ![cc-check-function-in-lib pthread_mutexattr_init pthread]} {
    user-error "Missing required pthread bits"
  }
  define LDFLAGS_PTHREAD [get-define lib_pthread_create]
  undefine lib_pthread_create
} {
  msg-result no
  add-feature-flag -DSQLITE_THREADSAFE=0
  define LDFLAGS_PTHREAD ""
}

########################################################################
# Do we want to support release?
#
# Maintenance note: this might be irrelevant with an autosetup port,
# as it appears to be related to libtool (part of the autotools).
#
if {0} {
  hwaci-if-opt-truthy releasemode {
    msg-result "Release-mode build."
    set enable_releasemode 1
  } {
    msg-result "Non-release-mode build."
    set enable_releasemode 0
  }
}

if {0} {
  msg-checking "Checking whether to support shared library linked as release mode or not..."
  # XXX if test "$enable_releasemode" = "no"; then
  # XXX ALLOWRELEASE=""
  msg-result "no"
  # XXX else
  # XXX ALLOWRELEASE="-release `cat $srcdir/VERSION`"
  msg-result "yes"
  # XXX fi
  # XXX AC_SUBST ALLOWRELEASE
}

########################################################################
# Do we want temporary databases in memory?
#
if {1} {
  set ts [opt-val with-tempstore no]
  set tsn 1
  msg-checking "Use an in-ram database for temporary tables? "
  switch -- $ts {
    never  { set tsn 0 }
    no     { set tsn 1 }
    yes    { set tsn 2 }
    always { set tsn 3 }
    default {
      user-error "Invalid with-tempstore value \[$ts]. Use one of: never, no, yes, always"
    }
  }
  msg-result $ts
  define TEMP_STORE $tsn
  unset ts tsn
}

if {1} {
  ##########
  # Figure out what C libraries are required to compile programs
  # that use "readline()" library.
  hwaci-check-readline
} else {
  # Older impl solely for reference while porting...
  #
  # XXX TARGET_READLINE_LIBS=""
  # XXX TARGET_READLINE_INC=""
  # XXX TARGET_HAVE_READLINE=0
  # XXX TARGET_HAVE_EDITLINE=0
  if {[opt-bool editline]} {
    set with_editline $enableval
  } else {
    set with_editline auto
  }
  if {![opt-bool readline]} {
    set with_readline $enableval
  } else {
    set with_readline auto
  }

  # XXX if test x"$with_editline" != xno; then
  # XXX sLIBS=$LIBS
  # XXX LIBS=""
  # XXX TARGET_HAVE_EDITLINE=1
  if {[cc-check-function-in-lib readline edit]} {
    set with_readline no
  } else {
    # XXX TARGET_HAVE_EDITLINE=0
  }
  # XXX TARGET_READLINE_LIBS=$LIBS
  # XXX LIBS=$sLIBS
  # XXX fi
  # XXX if test x"$with_readline" != xno; then
  set found "yes"

  if {[opt-val with-readline-lib] ne {}} {
    set withval [lindex [opt-val with-readline-lib] end]
    set with_readline_lib $withval
  } else {
    set with_readline_lib "auto"
  }
  # XXX if test "x$with_readline_lib" = xauto; then
  # XXX save_LIBS="$LIBS"
  # XXX LIBS=""
  if {[cc-check-function-in-lib tgetent readline ncurses curses termcap]} {
    # XXX term_LIBS="$LIBS"
  } else {
    # XXX term_LIBS=""
  }
  if {[cc-check-function-in-lib readline readline]} {
    # XXX TARGET_READLINE_LIBS="-lreadline"
  } else {
    set found "no"
  }
  # XXX TARGET_READLINE_LIBS="$TARGET_READLINE_LIBS $term_LIBS"
  # XXX LIBS="$save_LIBS"
  # XXX else
  # XXX TARGET_READLINE_LIBS="$with_readline_lib"
  # XXX fi

  if {[opt-val with-readline-inc] ne {}} {
    set withval [lindex [opt-val with-readline-inc] end]
    set with_readline_inc $withval
  } else {
    set with_readline_inc "auto"
  }
  # XXX if test "x$with_readline_inc" = xauto; then
  if {[cc-check-includes readline.h]} {
    set found "yes"
  } else {
    set found "no"
    # XXX if test "$cross_compiling" != yes; then
    # XXX for dir in /usr /usr/local /usr/local/readline /usr/contrib /mingw; do
    # XXX for subdir in include include/readline; do
    # XXX AC_CHECK_FILE $dir/$subdir/readline.h found=yes
    # XXX if test "$found" = "yes"; then
    # XXX TARGET_READLINE_INC="-I$dir/$subdir"
    # XXX break
    # XXX fi
    # XXX done
    # XXX test "$found" = "yes" && break
    # XXX done
    # XXX fi
  }
  # XXX else
  # XXX TARGET_READLINE_INC="$with_readline_inc"
  # XXX fi

  # XXX if test x"$found" = xno; then
  # XXX TARGET_READLINE_LIBS=""
  # XXX TARGET_READLINE_INC=""
  # XXX TARGET_HAVE_READLINE=0
  # XXX else
  # XXX TARGET_HAVE_READLINE=1
  # XXX fi
  # XXX fi
  if {[opt-val with-linenoise] ne {}} {
    set withval [lindex [opt-val with-linenoise] end]
    set with_linenoise $withval
  } else {
    set with_linenoise "no"
  }
  # XXX if test "x$with_linenoise" != "xno"; then
  # XXX TARGET_HAVE_READLINE=0
  # XXX TARGET_HAVE_EDITLINE=0
  # XXX TARGET_HAVE_LINENOISE=1
  # XXX TARGET_READLINE_INC="-I${with_linenoise}"
  # XXX TARGET_READLINE_LIBS="${with_linenoise}/linenoise.c"
  # XXX echo "using linenoise source code at ${with_linenoise}"
  # XXX else
  # XXX TARGET_HAVE_LINENOISE=0
  # XXX echo "not using linenoise"
  # XXX fi

  # XXX AC_SUBST TARGET_READLINE_LIBS
  # XXX AC_SUBST TARGET_READLINE_INC
  # XXX AC_SUBST TARGET_HAVE_READLINE
  # XXX AC_SUBST TARGET_HAVE_EDITLINE
  # XXX AC_SUBST TARGET_HAVE_LINENOISE
}

hwaci-if-opt-truthy load-extension {
  if {[cc-check-function-in-lib dlopen dl]} {
    define LDFLAGS_DLOPEN [get-define lib_dlopen]
    undefine lib_dlopen
  } else {
    user-error "dlopen() not found. Use --disable-load-extension to bypass this check."
  }
} {
  define LDFLAGS_DLOPEN ""
  add-feature-flag {-DSQLITE_OMIT_LOAD_EXTENSION=1}
  msg-result "Disabling loadable extensions."
}

hwaci-if-opt-truthy math {
  if {![cc-check-function-in-lib ceil m]} {
    user-error "Cannot find libm functions. Use --disable-math to bypass this."
  }
  define LDFLAGS_MATH [get-define lib_ceil]
  undefine lib_ceil
  add-feature-flag {-DSQLITE_ENABLE_MATH_FUNCTIONS}
  msg-result "Enabling math SQL functions"
} {
  define LDFLAGS_MATH ""
  msg-result "Disabling math SQL functions"
}

hwaci-if-opt-truthy json {
  msg-result "Enabling JSON SQL functions"
} {
  add-feature-flag {-DSQLITE_OMIT_JSON}
  msg-result "Disabling JSON SQL functions"
}

if {0} {
  # is this still relevant?

  #########
  # attempt to duplicate any OMITS and ENABLES into the ${OPT_FEATURE_FLAGS} parameter
  # XXX for option in $CFLAGS $CPPFLAGS
  # XXX do
  # XXX case $option in
  # XXX -DSQLITE_OMIT*) OPT_FEATURE_FLAGS="$OPT_FEATURE_FLAGS $option";;
  # XXX -DSQLITE_ENABLE*) OPT_FEATURE_FLAGS="$OPT_FEATURE_FLAGS $option";;
  # XXX esac
  # XXX done
  # XXX AC_SUBST OPT_FEATURE_FLAGS

  # attempt to remove any OMITS and ENABLES from the $(CFLAGS) parameter
  # XXX ac_temp_CFLAGS=""
  # XXX for option in $CFLAGS
  # XXX do
  # XXX case $option in
  # XXX -DSQLITE_OMIT*) ;;
  # XXX -DSQLITE_ENABLE*) ;;
  # XXX *) ac_temp_CFLAGS="$ac_temp_CFLAGS $option";;
  # XXX esac
  # XXX done
  # XXX CFLAGS=$ac_temp_CFLAGS

  # attempt to remove any OMITS and ENABLES from the $(CPPFLAGS) parameter
  # XXX ac_temp_CPPFLAGS=""
  # XXX for option in $CPPFLAGS
  # XXX do
  # XXX case $option in
  # XXX -DSQLITE_OMIT*) ;;
  # XXX -DSQLITE_ENABLE*) ;;
  # XXX *) ac_temp_CPPFLAGS="$ac_temp_CPPFLAGS $option";;
  # XXX esac
  # XXX done
  # XXX CPPFLAGS=$ac_temp_CPPFLAGS

  # attempt to remove any OMITS and ENABLES from the $(BUILD_CFLAGS) parameter
  # XXX ac_temp_BUILD_CFLAGS=""
  # XXX for option in $BUILD_CFLAGS
  # XXX do
  # XXX case $option in
  # XXX -DSQLITE_OMIT*) ;;
  # XXX -DSQLITE_ENABLE*) ;;
  # XXX *) ac_temp_BUILD_CFLAGS="$ac_temp_BUILD_CFLAGS $option";;
  # XXX esac
  # XXX done
  # XXX BUILD_CFLAGS=$ac_temp_BUILD_CFLAGS
}

########################################################################
# Emscripten SDK for building the web-based wasm components.
#
if {[hwaci-check-emsdk]} {
  set wrapper $srcdir/tool/emcc.sh
  define EMCC_WRAPPER $wrapper
  hwaci-make-from-dot-in $wrapper
  catch {exec chmod u+x $wrapper}
  unset wrapper
} else {
  define EMCC_WRAPPER ""
  catch {exec rm -f $srcdir/tool/emcc.sh}
}

proc affirm-have-math {} {
  if {![cc-check-function-in-lib log m]} {
    user-error "Missing required math APIs"
  }
  define LDFLAGS_MATH [get-define lib_log ""]
}

########################################################################
# Handle various SQLITE_ENABLE_... feature flags.
foreach {boolFlag featureFlag ifSetEvalThis} {
  all         {} {
    hwaci-opt-set fts4
    hwaci-opt-set fts5
    hwaci-opt-set geopoly
    hwaci-opt-set rtree
    hwaci-opt-set session
  }
  fts4         -DSQLITE_ENABLE_FTS4    {affirm-have-math}
  fts5         -DSQLITE_ENABLE_FTS5    {affirm-have-math}
  geopoly      -DSQLITE_ENABLE_GEOPOLY {hwaci-opt-set rtree}
  rtree        -DSQLITE_ENABLE_RTREE   {}
  session      {-DSQLITE_ENABLE_SESSION -DSQLITE_ENABLE_PREUPDATE_HOOK} {}
  update-limit -DSQLITE_ENABLE_UPDATE_DELETE_LIMIT {}
  memsys3      {} {
    if {[opt-bool memsys5]} {
      msg-result "NOT enabling memsys3 because memsys5 is enabled."
    } else {
      add-feature-flag -DSQLITE_ENABLE_MEMSYS3
    }
  }
  memsys5      -DSQLITE_ENABLE_MEMSYS5 {}
} {
  hwaci-if-opt-truthy $boolFlag {
    add-feature-flag $featureFlag
    msg-result "Enabling $boolFlag"
    eval $ifSetEvalThis
  } {
    msg-result "Not enabling $boolFlag"
  }
}

########################################################################
# Maybe extend JimTCL a bit. As of this writing (2024-09-27) it only
# needs -DHAVE_REALPATH or -DHAVE__FULLPATH to be compatible with our
# code generators. It can, however, be slightly extended via
# easy-to-detect features, should we need them.
if {0 && "" ne [get-define CFLAGS_JIMSH]} {
  foreach jimFunc {opendir fsync isascii} {
    if {[cc-check-functions $jimFunc]} {
      define-append CFLAGS_JIMSH -DHAVE_[string toupper $jimFunc]
    }
  }
  #foreach jimDef {HAVE_UNISTD_H HAVE_DIRENT_H} {
  #  if {[is-defined $jimDef]} {
  #    define-append CFLAGS_JIMSH -D$jimDef
  #  }
  #}
  define-append CFLAGS_JIMSH -DHAVE_LONG_LONG; # SQLite relies on long long, so we know it's available
}; # JimTCL

define ENABLE_SHARED $enable_shared

########################################################################
# Generate the output files.
#
if {1} {
  hwaci-make-from-dot-in Makefile
  hwaci-make-from-dot-in sqlite3.pc
  if {1} {
    # for sqlite_cfg.h
    define PACKAGE_URL {https://sqlite.org}
    define PACKAGE_VERSION [get-define VERSION]
  }
  if {0} {
    # Requires a hand-written sqlite_cfg.h.in...
    hwaci-make-from-dot-in sqlite_cfg.h
    # vs...
  } else {
    # Requires no input template...
    make-config-header sqlite_cfg.h \
      -bare {SIZEOF_* HAVE_DECL_*} \
      -auto {HAVE_* PACKAGE_*} -none *
  }
  #hwaci-make-from-dot-in ext/wasm/GNUmakefile
}

set oFF [get-define OPT_FEATURE_FLAGS]
if {"" ne $oFF} {
  define OPT_FEATURE_FLAGS [lsort -unique $oFF]
  msg-result "Final feature flags: [get-define OPT_FEATURE_FLAGS]"
}
set oFF [get-define OPT_SHELL]
if {"" ne $oFF} {
  msg-result "Final shell opts: [get-define OPT_SHELL]"
}
unset oFF

hwaci-if-opt-truthy dump-defines {
  global DUMP_DEFINES_FILE
  msg-result "--dump-defines is creating file: $DUMP_DEFINES_FILE"
  make-config-header $DUMP_DEFINES_FILE \
    -bare {OPT_FEATURE_FLAGS SQLITE_OS* SQLITE_DEBUG LDFLAGS_* USE_*} \
    -str {BIN_* CC LD AR} \
    -auto {*}
  # achtung: ^^^^ whichever SQLITE_OS_foo flag which is set to 0 will
  # get _undefined_ here unless it's part of the -bare set.
  if {0} {
    foreach x [all-defines] {
      puts "\t$x"
    }
  }
}
