summaryrefslogtreecommitdiff
path: root/src/plopconfig.erl
blob: 00b29df97c19d1ead1c1350991045075a87386c4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
%%% Copyright (c) 2017, NORDUnet A/S.
%%% See LICENSE for licensing information.

-module(plopconfig).
-export([get_env/1, get_env/2, init_table/0, load_config/0]).

-define(PLOPCONFIG_TABLE, plopconfig).

init_table() ->
    case ets:info(?PLOPCONFIG_TABLE) of
	undefined ->
	    ok;
	_ ->
	    ets:delete(?PLOPCONFIG_TABLE)
    end,
    ets:new(?PLOPCONFIG_TABLE, [set, public, named_table]),
    load_config().

keys() ->
    KeyList = lists:map(fun ({Key, _Value}) -> Key end,
                        ets:tab2list(?PLOPCONFIG_TABLE)),
    sets:from_list(KeyList).

load_config() ->
    {ok, Filename} = application:get_env(plop, plopconfig),
    {ok, File} = file:consult(Filename),
    OldKeys = keys(),
    lists:foreach(
      fun ({Key, Value}) ->
              true = ets:insert(?PLOPCONFIG_TABLE, {Key, Value})
      end, hd(File)),
    NewKeys = keys(),
    RemovedKeys = sets:subtract(OldKeys, NewKeys),
    lists:foreach(fun (Key) ->
                          ets:delete(?PLOPCONFIG_TABLE, Key)
                  end, sets:to_list(RemovedKeys)),
    lager:info("loaded config: new keys ~p old keys ~p removed keys ~p",
               [sets:to_list(NewKeys),
                sets:to_list(OldKeys),
                sets:to_list(RemovedKeys)]),
    ok.

get_env(Key, DefaultValue) ->
    case get_env(Key) of
        {ok, Value} ->
            Value;
        _ ->
            DefaultValue
    end.

get_env(Key) ->
    case ets:lookup(?PLOPCONFIG_TABLE, Key) of
        [{_, Value}] ->
            {ok, Value};
        [] ->
            undefined
    end.