%% -*- mode: erlang;erlang-indent-level: 4;indent-tabs-mode: nil -*-
%% ex: ts=4 sw=4 ft=erlang et

case crypto:start() of
    {error, {already_started, crypto}} ->
        ok;
    ok ->
        ok
end.

AddErlcDefines = fun(Cfg, Defines) ->
                         {value, {erl_opts, ErlOpts}} =
                             lists:keysearch(erl_opts, 1, Cfg),
                         NewOpts = Defines ++ ErlOpts,
                         lists:keyreplace(erl_opts, 1, Cfg, {erl_opts, NewOpts})
                 end.

RandCheck = fun(Cfg) ->
                    case code:which(rand) of
                        non_existing ->
                            Cfg;
                        _ ->
                            D = [{d, 'HAVE_RAND_MOD'}],
                            AddErlcDefines(Cfg, D)
                        end
            end.

CryptoCheck = fun(Cfg) ->
                      case erlang:function_exported(
                             crypto, strong_rand_bytes, 1)
                      of
                          true ->
                              D = [{d, 'HAVE_CRYPTO_STRONG_RAND_BYTES'}],
                              AddErlcDefines(Cfg, D);
                          false ->
                              Cfg
                      end
              end.

StacktraceCheck = fun(Cfg) ->
                          case erlang:system_info(otp_release) >= "21" of
                              true ->
                                  D = [{d, 'HAVE_STACKTRACE_MATCH'}],
                                  AddErlcDefines(Cfg, D);
                              false ->
                                  Cfg
                          end
                  end.

Config0 = RandCheck(CONFIG).
Config1 = CryptoCheck(Config0).
Config2 = StacktraceCheck(Config1).

MaybeReportConfig = fun(Cfg) ->
                            case os:getenv("DEBUG_CONFIG") of
                                false ->
                                    Cfg;
                                _ ->
                                    io:format(standard_error,
                                              "rebar config:~n~p~n", [Cfg]),
                                    Cfg
                            end
                    end.

MaybeReportConfig(Config2).
