summaryrefslogtreecommitdiffstats
path: root/src/core/ephraim_config.erl
blob: 6c493514b2b131daf19b37b265bf4def45436f8d (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
-module(ephraim_config).
-compile([debug_info, export_all]).

-spec init() -> ok.
init() ->
    register(ephraim_config, self()),
    ephraim ! {self(), started},
    
    {ok, Terms} = file:consult(config_path() ++ "/ephraim.cfg"),
    Config = dict:from_list(lists:map(fun(Term) -> {element(1, Term), Term} end, Terms)),
    
    loop(Config).


-spec config_path() -> string().
config_path() ->
    Path = case os:getenv("XDG_CONFIG_HOME") of
	       false ->
		   os:getenv("HOME") ++ "/.config";
	       ConfigHome ->
		   ConfigHome
	   end ++ "/ephraim",
    case file:read_file_info(Path) of
	{ok, _} ->
	    ok;
	{error, _} ->
	    file:make_dir(Path)
    end,
    Path.


-spec get(atom()) -> tuple() | error.
get(Key) ->
    ephraim_config ! {self(), get, Key},
    receive
	{config, ok, Key, Value} ->
	    Value;
	{config, error, Key} ->
	    error
    end.
	
-spec loop(dict()) -> ok.
loop(Config) ->
    receive
	stop ->
	    ok;
	{From, get, Key} ->
	    case dict:find(Key, Config) of
		{ok, Value} ->
		    From ! {config, ok, Key, Value};
		error ->
		    From ! {config, error, Key}
	    end,
	    loop(Config)
    end.