-module(p11p_config). -behaviour(gen_server). %% API -export([start_link/0]). -export([config/0]). -export([tokens/0]). -export([modules_for_token/1]). %% Genserver callbacks. -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). %% Records and types. -include("p11p_defs.hrl"). %% Genserver state. -record(state, { tokens :: [token()] }). %%%%%%%%%%%%%%%%%%%% %% API. start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). config() -> gen_server:call(?MODULE, config). -spec tokens() -> [token()]. tokens() -> gen_server:call(?MODULE, tokens). -spec modules_for_token(token()) -> [p11module()]. modules_for_token(Token) -> gen_server:call(?MODULE, {modules_for_token, Token}). %%%%%%%%%%%%%%%%%%%% %% Genserver callbacks. init(_Args) -> State = init_state(), {ok, State}. handle_call(config, _From, State) -> {reply, State, State}; handle_call(tokens, _From, #state{tokens = Tokens} = State) -> {reply, Tokens, State}; handle_call({modules_for_token, _Token}, _From, #state{tokens = _Tokens} = State) -> Reply = [#p11module{name="FIXME", path="FIXME"}], {reply, Reply, State}; handle_call(Request, _From, State) -> lager:warning("Unhandled call: ~p", [Request]), {reply, unhandled, State}. handle_cast(Message, State) -> lager:warning("Unhandled cast: ~p", [Message]), {noreply, State}. handle_info(Info, State) -> lager:warning("Unhandled info: ~p", [Info]), {noreply, State}. terminate(_Reason, _State) -> ok. code_change(_OldVersion, State, _Extra) -> {ok, State}. %%%%%%%%%%%%%%%%%%%% %% Private. init_state() -> #state { tokens = init_tokens(application:get_env(p11p, groups, [])) }. init_tokens(Tokens) -> [new_token(T) || T <- Tokens]. -spec new_token({string(), [tuple()]}) -> token(). new_token({Name, Settings}) -> #token{ name = Name, modules = [new_module(M) || M <- proplists:get_value(modules, Settings, [])] }. new_module({Name, Path}) -> #p11module{ name = Name, path = Path }. %%%%%%%%%%%%%% %% Unit tests. -include_lib("eunit/include/eunit.hrl"). tokens_test_() -> {setup, fun() -> init_tokens( [ {"vtoken0", [{modules, [{"bogusmod0_0", "/path/to/bogusmod0_0"}, {"bogusmod0_1", "/path/to/bogusmod0_1"} ]}]}, {"vtoken1", [{modules, [{"bogusmod1_0", "/path/to/bogusmod1_0"}]}]} ]) end, fun(_) -> ok end, fun(Conf) -> [?_assertEqual( [ {token,"vtoken0",[{p11module,"bogusmod0_0", "/path/to/bogusmod0_0"}, {p11module,"bogusmod0_1", "/path/to/bogusmod0_1"}]}, {token,"vtoken1",[{p11module,"bogusmod1_0", "/path/to/bogusmod1_0"}]} ], Conf)] end}.