%%% -*- mode: erlang -*-

CurlVerHex = string:strip(os:cmd("curl-config --vernum 2>/dev/null"), right, $\n).
%% Empty (curl-config not on PATH) or non-hex output would otherwise abort the
%% whole build with an opaque badarg before any C compile diagnostic. Fall back
%% to 0 (all feature macros off) and let the C compile surface the real error.
CurlVerInt = try erlang:list_to_integer(CurlVerHex, 16)
             catch error:badarg ->
                 io:format("katipo: 'curl-config --vernum' returned ~p; "
                           "disabling curl feature detection. Is libcurl "
                           "development installed and on PATH?~n", [CurlVerHex]),
                 0
             end.

%% CURLOPT_TCP_FASTOPEN since 7.49.0 (471296)
CurlOptTcpFastopen = case CurlVerInt >= 471296 of
                         true ->
                             [{d, tcp_fastopen_available}];
                         false ->
                             []
                     end.

%% CURLOPT_UNIX_SOCKET_PATH since 7.40.0 (468992)
CurlOptUnixSocketPath = case CurlVerInt >= 468992 of
                            true ->
                                [{d, unix_socket_path_available}];
                            false ->
                                []
                        end.

%% CURLOPT_DOHURL since 7.62.0 (474624)
CurlOptDOHURL = case CurlVerInt >= 474624 of
                            true ->
                                [{d, doh_url_available}];
                            false ->
                                []
                        end.

%% CURLOPT_SSLKEY_BLOB since 7.71.0 (476928)
CurlOptSSLKeyBlob = case CurlVerInt >= 476928 of
                                true ->
                                    [{d, sslkey_blob_available}];
                                false ->
                                    []
                        end.

%% CURL_HTTP_VERSION_3 since 7.66.0 (475648)
CurlOptHttp3 = case CurlVerInt >= 475648 of
                   true ->
                       [{d, http3_available}];
                   false ->
                       []
               end.

{_, ErlOpts} = lists:keyfind(erl_opts, 1, CONFIG).

ErlOpts2 = ErlOpts ++
           CurlOptTcpFastopen ++
           CurlOptUnixSocketPath ++
           CurlOptDOHURL ++
           CurlOptSSLKeyBlob ++
           CurlOptHttp3.

Config1 = lists:keystore(erl_opts, 1, CONFIG, {erl_opts, ErlOpts2}).

case os:getenv("TRAVIS") of
    "true" ->
        JobId   = os:getenv("TRAVIS_JOB_ID"),
        lists:keystore(coveralls_service_job_id, 1, Config1, {coveralls_service_job_id, JobId});
    _ ->
        Config1
end.
