#!/bin/sh
set -eu

prefix=/usr/local
enable_s7=1
cc=${CC:-cc}

usage() {
  echo "usage: ./configure [--prefix=PATH] [--enable-s7] [CC=compiler]"
  echo "requires a C99 compiler, make, libsodium, libcurl; S7 is bundled and required"
}

for arg in "$@"; do
  case "$arg" in
    --prefix=*) prefix=${arg#*=} ;;
    --enable-s7) enable_s7=1 ;;
    --disable-s7) echo "configure: error: S7 is required for JSON and Scheme data handling" >&2; exit 1 ;;
    --help|-h) usage; exit 0 ;;
    CC=*) cc=${arg#CC=} ;;
    *) echo "configure: unknown option: $arg" >&2; usage >&2; exit 1 ;;
  esac
done

log=config.log
: > "$log"
echo "configure: checking build tools"
for tool in "$cc" ar ranlib install make; do
  if ! command -v "$tool" >/dev/null 2>&1; then
    echo "configure: error: required tool '$tool' was not found" | tee -a "$log" >&2
    exit 1
  fi
done

tmp_c=conftest-$$.c
tmp_exe=conftest-$$
trap 'rm -f "$tmp_c" "$tmp_exe"' EXIT HUP INT TERM
cat > "$tmp_c" <<'EOF'
#include <sodium.h>
int main(void) { return sodium_init() < 0; }
EOF

sodium_cflags=
sodium_libs=-lsodium
curl_cflags=
curl_libs=-lcurl
if command -v pkg-config >/dev/null 2>&1 && pkg-config --exists libsodium; then
  sodium_cflags=$(pkg-config --cflags libsodium)
  sodium_libs=$(pkg-config --libs libsodium)
fi
if ! "$cc" $sodium_cflags "$tmp_c" $sodium_libs -o "$tmp_exe" >>"$log" 2>&1; then
  echo "configure: error: libsodium headers and library are required" | tee -a "$log" >&2
  exit 1
fi

if command -v pkg-config >/dev/null 2>&1 && pkg-config --exists libcurl; then
  curl_cflags=$(pkg-config --cflags libcurl)
  curl_libs=$(pkg-config --libs libcurl)
fi
cat > "$tmp_c" <<'EOF'
#include <curl/curl.h>
int main(void) { CURL *c = curl_easy_init(); if (c) curl_easy_cleanup(c); return 0; }
EOF
if ! "$cc" $curl_cflags "$tmp_c" $curl_libs -o "$tmp_exe" >>"$log" 2>&1; then
  echo "configure: error: libcurl headers and library are required for Dat name resolution" | tee -a "$log" >&2
  exit 1
fi

cat > config.mk <<EOF
# Generated by ./configure. Edit configure arguments, not this file.
PREFIX = $prefix
CC = $cc
AR = ar
RANLIB = ranlib
INSTALL = install
SODIUM_CFLAGS = $sodium_cflags
SODIUM_LIBS = $sodium_libs
CURL_CFLAGS = $curl_cflags
CURL_LIBS = $curl_libs
ENABLE_S7 = $enable_s7
CPPFLAGS += \$(SODIUM_CFLAGS)
EOF

cat > config.h <<EOF
#ifndef DATGPT_CONFIG_H
#define DATGPT_CONFIG_H
#define DATGPT_HAVE_SODIUM 1
#define DATGPT_ENABLE_S7 $enable_s7
#define DATGPT_PREFIX "$prefix"
#endif
EOF

echo "configure: prefix:      $prefix"
echo "configure: compiler:    $cc"
echo "configure: libsodium:   $sodium_libs"
echo "configure: Dat name transport: $curl_libs"
echo "configure: S7 bindings: required"
echo "configure: created config.mk and config.h"
