#!/bin/sh
#
# Build examples/fossil on NixOS.
#
# Usage: tools/nixos-fossil.sh [make arguments]
#
# Fossil's configure takes one directory per dependency and expects include/
# and lib/ below it. This builds a directory of Nix symlinks for configure.
#
# See doc/lumo-build-nixos.md.

# No set -u: /etc/set-environment reads unset variables.
set -e
. /etc/set-environment 2>/dev/null || true
export PATH=/root/.local/bin:$PATH
export PERL5LIB="/root/.local/lib/perl5/site_perl/5.42.0:$PERL5LIB"

DIR=${LUMO_NIXOS_DIR:-/root/nixos-deps}

link_dep() { # name devglob libglob
	dev=$(ls -d /nix/store/$2 2>/dev/null | head -1)
	# the -dev output has a lib/ holding only pkgconfig and cmake files
	lib=$(ls -d /nix/store/$3 2>/dev/null | grep -v -- '-dev/' | head -1)
	[ -n "$dev" ] && [ -n "$lib" ] || { echo "cannot locate $1 outputs" >&2; exit 1; }
	rm -rf "$DIR/$1"
	mkdir -p "$DIR/$1"
	ln -s "$dev/include" "$DIR/$1/include"
	ln -s "$lib"         "$DIR/$1/lib"
	echo "# $1: include -> $dev/include, lib -> $lib"
}

link_dep zlib    '*zlib-[0-9]*-dev'  '*zlib-[0-9]*[0-9]/lib'
link_dep openssl '*openssl-3*-dev'   '*openssl-3.[0-9.]*/lib'

cd "$(dirname "$0")/.."
exec make fossil \
  LUMO_FOSSIL_CONFIGURE_ARGS="--disable-fusefs --with-zlib=$DIR/zlib --with-openssl=$DIR/openssl" \
  LUMO_EXTRA_LDFLAGS="-L$DIR/zlib/lib -L$DIR/openssl/lib -Wl,-rpath,$DIR/zlib/lib -Wl,-rpath,$DIR/openssl/lib" \
  "$@"
