#!/bin/sh
# Select the TLS backend and generate src/Makevars (design §13, roadmap S9/S19).
#
# zuhttp's premise (§2) is the platform's own TLS stack and trust store, with
# no bundled cryptography library and no bundled certificate bundle. This
# script therefore picks the SYSTEM backend where one exists and only falls
# back to linking OpenSSL where the platform provides nothing usable.
#
#   macOS   Network.framework + SecTrust  nothing to install, nothing bundled
#   Linux   system OpenSSL (dynamic)      the platform's own shared library
#
# macOS is Network.framework (D-63, W13): Secure Transport was deprecated,
# stopped at TLS 1.2 and cost an --as-cran NOTE. Network.framework owns the
# socket, so on macOS the TLS backend dials HTTPS itself, CONNECT included
# (D-71); see spike/network-framework/FINDINGS.md.
set -eu

: "${R_HOME:=$(R RHOME)}"
CC=$("${R_HOME}/bin/R" CMD config CC)
CFLAGS=$("${R_HOME}/bin/R" CMD config CFLAGS)
UNAME=$(uname -s)

SSL_CFLAGS=""
SSL_LIBS=""
TLS_OBJ=""

if [ "$UNAME" = "Darwin" ]; then
    # --- macOS: the system stack. No OpenSSL, nothing to install. ----------
    TLS_OBJ="zuh_tls_nw.o"
    SSL_LIBS="-framework Network -framework Security -framework CoreFoundation"
    echo "configure: TLS backend = Network.framework + SecTrust (system)"

    tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT
    cat > "$tmp/t.c" <<'CEOF'
#include <Network/Network.h>
#include <Security/Security.h>
int main(void) {
    /* The verify block that keeps trust ours (§13.1), and the non-deprecated
       trust API it calls. Checked here so a toolchain without them fails at
       install rather than at the first HTTPS request. */
    (void)&sec_protocol_options_set_verify_block;
    (void)&SecTrustEvaluateWithError;
    return nw_parameters_create_secure_tcp(NW_PARAMETERS_DEFAULT_CONFIGURATION,
                                           NW_PARAMETERS_DEFAULT_CONFIGURATION) ? 0 : 1;
}
CEOF
    # shellcheck disable=SC2086
    if ! $CC $CFLAGS -o "$tmp/t" "$tmp/t.c" $SSL_LIBS >/dev/null 2>&1; then
        echo "configure: Network.framework did not link. This is unexpected on macOS." >&2
        exit 1
    fi
    echo "configure: Network.framework links; SecTrustEvaluateWithError present"
else
    # --- everything else: the system OpenSSL, dynamically linked ----------
    TLS_OBJ="zuh_tls_openssl.o"
    if command -v pkg-config >/dev/null 2>&1 && pkg-config --exists openssl 2>/dev/null; then
        SSL_CFLAGS=$(pkg-config --cflags openssl)
        SSL_LIBS=$(pkg-config --libs openssl)
        echo "configure: TLS backend = OpenSSL $(pkg-config --modversion openssl) (system)"
    else
        for p in /usr/local /usr /opt/local; do
            if [ -f "$p/include/openssl/ssl.h" ]; then
                SSL_CFLAGS="-I$p/include"
                SSL_LIBS="-L$p/lib -lssl -lcrypto"
                echo "configure: OpenSSL headers found under $p"
                break
            fi
        done
    fi

    if [ -z "$SSL_LIBS" ]; then
        cat >&2 <<'MSG'
configure: could not find OpenSSL.

zuhttp uses the system TLS stack and does not bundle one. Install the
development package and retry:

  Debian/Ubuntu   apt-get install libssl-dev
  Fedora/RHEL     dnf install openssl-devel
  Alpine          apk add openssl-dev
MSG
        exit 1
    fi

    tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT
    cat > "$tmp/t.c" <<'CEOF'
#include <openssl/ssl.h>
#include <openssl/x509v3.h>
int main(void) {
    SSL_CTX *c = SSL_CTX_new(TLS_client_method());
    SSL *s = c ? SSL_new(c) : 0;
    /* §13.5: hostname verification comes from the library, never from a
       hand-rolled comparison, so this symbol is a hard requirement. */
    if (s) SSL_set1_host(s, "example.com");
    return c ? 0 : 1;
}
CEOF
    # shellcheck disable=SC2086
    if ! $CC $CFLAGS $SSL_CFLAGS -o "$tmp/t" "$tmp/t.c" $SSL_LIBS >/dev/null 2>&1; then
        echo "configure: found OpenSSL headers but could not link a test program." >&2
        echo "configure: CFLAGS=$SSL_CFLAGS LIBS=$SSL_LIBS" >&2
        exit 1
    fi
    echo "configure: OpenSSL links, and SSL_set1_host is available"
fi

sed -e "s|@SSL_CFLAGS@|$SSL_CFLAGS|g" \
    -e "s|@SSL_LIBS@|$SSL_LIBS|g" \
    -e "s|@TLS_OBJ@|$TLS_OBJ|g" \
    src/Makevars.in > src/Makevars
echo "configure: wrote src/Makevars (TLS object: $TLS_OBJ)"
