summaryrefslogtreecommitdiffstats
path: root/src/core/ephraim_config.erl
blob: dd9e64d2c4f5804eeefef3f0b1afbbd79d50e430 (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
58
59
-module(ephraim_config).
-behaviour(gen_server).

-export([start_link/0]).
-export([get/1]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).

-spec start_link() -> {ok, pid()}.
start_link() ->
    gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).

-spec init(term()) -> {ok, dict()}.
init(_Args) ->
    process_flag(trap_exit, true),
    
    {ok, Terms} = file:consult(config_path() ++ "/ephraim.cfg"),
    Config = dict:from_list(lists:map(fun(Term) -> {element(1, Term), Term} end, Terms)),
    
    {ok, 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) ->
    gen_server:call(?MODULE, {get, Key}).


-spec handle_call(term(), {pid(), term()}, dict()) -> {reply, tuple() | error, dict()}.
handle_call({get, Key}, _From, Config) ->
    case dict:find(Key, Config) of
	{ok, Value} ->
	    {reply, Value, Config};
	error ->
	    {reply, error, Config}
    end.

handle_cast(_Msg, Config) ->
    {noreply, Config}.
handle_info(_Msg, Config) ->
    {noreply, Config}.
terminate(_Reason, _Config) ->
    ok.
code_change(_OldVersion, Config, _Extra) ->
    {ok, Config}.