#!/usr/bin/env sh
# bootstrap script
# run this to generate the configure script and other files needed
# by the build system (e.g. source files to compile).

set -e

# Make sure we're in the right directory
if [ ! -f "configure.ac" ]; then
    echo "Error: configure.ac not found. Run this script from the project root directory."
    exit 1
fi

########################################

echo "Generating source file list..."
SOURCES_FILE="src/Makefile.sources"
mkdir -p "$(dirname "$SOURCES_FILE")"

cat > "$SOURCES_FILE" << EOF
# Automatically generated by autogen.sh - DO NOT EDIT
neosu_SOURCES = \\
EOF

find src libraries -type f '(' -name "*.cpp" -o -name "*.c" ')' | LC_ALL=C sort | \
    sed 's/$/ \\/' | \
    sed 's/^/\t/' >> "$SOURCES_FILE"

echo "\$(NULL)" >> "$SOURCES_FILE"

# need to add these to dependency tracking manually, `.incbin` does not track changes to binary includes
cat >> "$SOURCES_FILE" << EOF
EXTRA_BINDEPS = \\
EOF

find assets/shaders -type f | LC_ALL=C sort | \
    sed 's/$/ \\/' | \
    sed 's/^/\t/' >> "$SOURCES_FILE"

echo "\$(NULL)" >> "$SOURCES_FILE"

mkdir -p "$(dirname build-aux)"

########################################

check_tool() {
    if ! command -v "$1" >/dev/null 2>&1; then
        echo "Error: $1 not found. Please install $2."
        exit 1
    fi
}

check_tool "aclocal" "automake"
check_tool "automake" "automake"
check_tool "autoconf" "autoconf"
check_tool "pkgconf" "pkgconf"

echo "Running autotools..."
autoreconf -fiv

echo "
Bootstrap complete. You can now build neosu either:

For development (recommended, out-of-tree build):
  mkdir build
  cd build
  ../configure [options]
  make
  make install

For end-users (in-tree build):
  ./configure [options]
  make
  make install

Some configure options:
  --prefix=/usr           Install to /usr instead of ./dist
  --enable-debug          Enable debug build
  --enable-native         Enable native CPU optimizations (-march=native -mtune=native)
  --enable-system-deps    Prefer sharing system dependencies instead of building them from source
  --disable-static        Try to build/link libraries dynamically instead of statically
  --enable-lto            Enable link-time optimization (default: used if available)

For a full list of options, run: ./configure --help
"
