%% ``The contents of this file are subject to the Erlang Public License,
%% Version 1.0, (the "License"); you may not use this file except in
%% compliance with the License. You may obtain a copy of the License at
%% http://www.erlang.org/EPL1_0.txt
%% 
%% Software distributed under the License is distributed on an "AS IS"
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%% 
%% The Original Code is Erlang-4.7.3, December, 1998.
%% 
%% The Initial Developer of the Original Code is Ericsson Telecom
%% AB. Portions created by Ericsson are Copyright (C), 1998, Ericsson
%% Telecom AB. All Rights Reserved.
%% 
%% Contributor(s): ______________________________________.''
%%
-module(application_controller).
-copyright('Copyright (c) 1991-97 Ericsson Telecom AB').
-vsn('$Revision: /main/release/free/3').
-vsn('$Revision: /main/release/free/3').
-author('mbj@erlang.ericsson.se').

-behaviour(gen_server).

%% External exports
-export([start/1, 
	 load_application/1, unload_application/1, 
	 start_application/2, stop_application/1,
	 control_application/1,
	 change_application_data/2, prep_config_change/0, config_change/1,
	 which_applications/0, loaded_applications/0, info/0,
	 get_pid_env/2, get_env/2, get_pid_all_env/1, get_all_env/1,
	 get_pid_key/2, get_key/2, get_pid_all_key/1, get_all_key/1,
	 get_master/1, get_application/1, get_application_module/1,
	 start_type/1, permit_application/2, do_config_diff/2,
	 set_env/3]).

%% Internal exports
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2,
	 init_starter/4, get_loaded/1]).

%% Test exports, only to be used from the test suites
-export([test_change_apps/2]).


-import(lists, [zf/2, map/2, foreach/2, foldl/3,
		keysearch/3, keydelete/3, keyreplace/4]).

-include("application_master.hrl").

-define(AC, ?MODULE). % Name of process

%%%-----------------------------------------------------------------
%%% The application_controller controls local applications only.  A
%%% local application can be loaded/started/stopped/unloaded and
%%% changed.  The control of distributed applications is taken care of
%%% by another process (default is dist_ac).
%%%
%%% When an application has been started (by a call to application:start)
%%% it can be running or not running (on this node).  For example,
%%% a distributed application must be started on all nodes, but
%%% may be running on one node at the time.
%%%
%%% The external API to this module is in the module 'application'.
%%% 
%%% The process that controls distributed applications (called dist
%%% ac).  calls application_controller:control_application(Name) to
%%% take responsibility for an application.  The interface between AC
%%% and the dist_ac process is message-based:
%%%
%%% AC                                        DIST AC
%%% ==                                        =======
%%%     --> {ac_load_application_req, Name}
%%%     <-- {ac_load_application_reply, Name, LoadReply}
%%%     --> {ac_start_application_req, Name}       (*)
%%%     <-- {ac_start_application_reply, Name, StartReply}
%%%     --> {ac_application_run, Name, Res}
%%%     --> {ac_application_not_run, Name, Res}
%%%     --> {ac_application_stopped, Name}
%%%     --> {ac_application_unloaded, Name}
%%%     <-- {ac_change_application_req, Name, Req} (**)
%%%
%%% Where LoadReply =
%%%   ok              - App is loaded
%%%   {error, R}      - An error occurred
%%% And StartReply =
%%%   start_it        - DIST AC decided that AC should start the app
%%%   {started, Node} - The app is started distributed at Node
%%%   not_started     - The app should not be running at this time
%%%   {takeover, Node}- The app should takeover from Node
%%%   {error, R}      - an error occurred
%%% And Req =
%%%   start_it        - DIST AC wants AC to start the app locally
%%%   stop_it         - AC should stop the app.
%%%   {takeover, Node, RestartType}
%%%                   - AC should start the app as a takeover
%%%   {failover, Node, RestartType}
%%%                   - AC should start the app as a failover
%%%   {started, Node} - The app is started at Node
%%%                     NOTE: The app must have been started at this node
%%%                     before this request is sent!
%%% And Res =
%%%   ok              - Application is started locally
%%%   {error, R}      - Start of application failed
%%%
%%% (*)
%%%  The call to application:start() doesn't return until the
%%%  ac_start_application_reply has been received by AC.  AC
%%%  itself is not blocked however.
%%% (**)
%%%  DIST AC gets ACK to its ac_change_application_req, but not as a
%%%  separate messgage.  Instead the normal messages are used as:
%%%   start_it   generates an ac_application_run
%%%   stop_it    generates an ac_application_not_run
%%%   takeover   generates an ac_application_run
%%%   started    doesn't generate anything
%%%
%%% There is a distinction between application:stop and stop_it
%%% from a dist ac process.  The first one stops the application,
%%% and resets the internal structures as they were before start was
%%% called.  stop_it stops the application, but just marks it as
%%% not being running.
%%%
%%% When a dist ac process has taken control of an application, no
%%% other process can take the control.
%%%-----------------------------------------------------------------

%%-----------------------------------------------------------------
%% Naming conventions:
%%   App = appl_descr()
%%   Appl = #appl
%%   AppName = atom()
%%   Application = App | AppName
%%-----------------------------------------------------------------
-record(state, {loading = [], starting = [], start_p_false = [], running = [],
		control = [], started = [], start_req = [], conf_data}).
%%-----------------------------------------------------------------
%% loading     = [{AppName, From}] - Load not yet finished
%% starting    = [{AppName, RestartType, Type, From}] - Start not
%%                 yet finished
%% start_p_false = [{AppName, RestartType, Type, From}] - Start not
%%                 executed because permit == false
%% running     = [{AppName, Pid}] - running locally (Pid == application_master)
%%               [{AppName, {distributed, Node}}] - running on Node
%% control     = [{AppName, Controller}]
%% started     = [{AppName, RestartType}] - Names of all apps that
%%                 have been started (but may not run because
%%                 permission = false)
%% conf_data   = [{AppName, Env}]
%% start_req   = [{AppName, From, Pid}] - list of all start requests
%% Id          = AMPid | undefined | {distributed, Node}
%% Env         = [{Key, Value}]
%%-----------------------------------------------------------------

-record(appl, {name, appl_data, descr, id, vsn, restart_type, inc_apps, apps}).
-define(wild_mods, {appl,'_',?wild_appl_mods,'_','_','_','_','_','_'}).

%%-----------------------------------------------------------------
%% Func: start/1
%% Args: KernelApp = appl_descr()
%%       appl_descr() = [{application, Name, [appl_opt()]}]
%%       appl_opt() = {description, string()}           |
%%                    {vsn, string()}                   |
%%                    {modules, [{atom(), vsn()}]}      |
%%                    {registered, [atom()]}            |
%%                    {applications, [{atom(), vsn()}]} |
%%                    {env, [{atom(), term()}]}         |
%%                    {mod, {Mod, StartArgs}}
%%       key() = atom(),
%%       value() = term()
%%       vsn() = term()
%% Purpose: Starts the application_controller.  This process starts all
%%          application masters for the applications.
%%          The kernel application is the only application that is
%%          treated specially.  The reason for this is that the kernel
%%          starts user.  This process is special because it should
%%          be group_leader for this process.
%% Pre: All modules are loaded, or will be loaded on demand.
%% Returns: {ok, Pid} | {error, Reason}
%%-----------------------------------------------------------------
start(KernelApp) ->
    gen_server:start_link({local, ?AC}, ?MODULE, KernelApp, []).


    

%%-----------------------------------------------------------------
%% Func: load_application/1
%% Args: Application = appl_descr() | atom()
%% Purpose: Loads an application.  Currently just inserts the
%%          application's env.
%% Returns: ok | {error, Reason}
%%-----------------------------------------------------------------
load_application(Application) ->
    gen_server:call(?AC, {load_application, Application}, infinity).

unload_application(AppName) ->
    gen_server:call(?AC, {unload_application, AppName}, infinity).

%%-----------------------------------------------------------------
%% Func: start_application/2
%% Args: Application = atom()
%%       RestartType = permanent | transient | temporary
%% Purpose: Starts a new application.
%%          The RestartType specifies what should happen if the
%%          application dies:
%%          If it is permanent, all other applications are terminated,
%%            and the application_controller dies.
%%          If it is transient, and the application dies normally,
%%            this is reported and no other applications are terminated.
%%            If the application dies abnormally, all other applications
%%            are terminated, and the application_controller dies.
%%          If it is temporary and the application dies this is reported
%%            and no other applications are terminated.  In this way,
%%            an application can run in test mode, without disturbing
%%            the other applications.
%%          The caller of this function is suspended until the application
%%          is started, either locally or distributed.
%% Returns: ok | {error, Reason}
%%-----------------------------------------------------------------
start_application(AppName, RestartType) ->
    gen_server:call(?AC, {start_application, AppName, RestartType}, infinity).

stop_application(AppName) ->
    gen_server:call(?AC, {stop_application, AppName}, infinity).

%%-----------------------------------------------------------------
%% Returns: [{Name, Descr, Vsn}]
%%-----------------------------------------------------------------
which_applications() ->
    gen_server:call(?AC, which_applications).    

loaded_applications() ->
    ets:filter(ac_tab,
	       fun([{{loaded, AppName}, #appl{descr = Descr, vsn = Vsn}}]) ->
		       {true, {AppName, Descr, Vsn}};
		  (_) ->
		       false
	       end,
	       []).

%% Returns some debug info
info() ->
    gen_server:call(?AC, info).    

control_application(AppName) ->
    gen_server:call(?AC, {control_application, AppName}, infinity).

%%-----------------------------------------------------------------
%% Func: change_application_data/2
%% Args: Applications = [appl_descr()]
%%       ConfData = [{AppName, [{atom(), term()}]}]
%% Purpose: Change all applications and their parameters on this node.
%%          This function should be used from a release handler, at
%%          the same time as the .app or start.boot file is
%%          introduced.  Note that during some time the ACs may have
%%          different view of e.g. the distributed applications.
%%          This is solved by syncing the release installation.
%%          However, strange things may happen if a node crashes
%%          and two other nodes have different opinons about who's
%%          gonna start the applications.  The release handler must
%%          shutdown each involved node in this case.
%%          Note that this function is used to change existing apps,
%%          adding new/deleting old isn't handled by this function.
%%          Changes an application's vsn, descr and env.
%% Returns: ok | {error, Reason}
%%          If an error occurred, the situation may be inconsistent,
%%          so the release handler must restart the node.  E.g. if
%%          some applicatation may have got new config data.
%%-----------------------------------------------------------------
change_application_data(Applications, ConfData) ->
    gen_server:call(?AC, 
		    {change_application_data, Applications, ConfData},
		    infinity).

prep_config_change() ->
    gen_server:call(?AC, 
		    prep_config_change,
		    infinity).


config_change(EnvPrev) ->
    gen_server:call(?AC, 
		    {config_change, EnvPrev},
		    infinity).



get_pid_env(Master, Key) ->
    case ets:match(ac_tab, {{application_master, '$1'}, Master}) of
	[[AppName]] -> get_env(AppName, Key);
	_ -> undefined
    end.

get_env(AppName, Key) ->
    case ets:lookup(ac_tab, {env, AppName, Key}) of
	[{_, Val}] -> {ok, Val};
	_ -> undefined
    end.

get_pid_all_env(Master) ->
    case ets:match(ac_tab, {{application_master, '$1'}, Master}) of
	[[AppName]] -> get_all_env(AppName);
	_ -> []
    end.

get_all_env(AppName) ->
    map(fun([Key, Val]) -> {Key, Val} end,
	ets:match(ac_tab, {{env, AppName, '$1'}, '$2'})).




get_pid_key(Master, Key) ->
    case ets:match(ac_tab, {{application_master, '$1'}, Master}) of
	[[AppName]] -> get_key(AppName, Key);
	_ -> undefined
    end.

get_key(AppName, Key) ->
    case ets:lookup(ac_tab, {loaded, AppName}) of
	[{_, {appl, AppName, ApplData, Desc, Id, Vsn, ResType, IncApps, Apps}}] ->
	    case Key of 
		description ->
		    {ok, Desc};
		id ->
		    {ok, Id};
		vsn ->
		    {ok, Vsn};
		applications ->
		    {ok, Apps};
		included_applications ->
		    {ok, IncApps};
		registered ->
		    {ok, ApplData#appl_data.regs};
		start_phases ->
		    {ok, ApplData#appl_data.phases};
		mod ->
		    {ok, ApplData#appl_data.mod};
		env ->
		    {ok, get_all_env(AppName)};
		modules ->
		    {ok, ApplData#appl_data.mods};
		maxP ->
		    {ok, ApplData#appl_data.maxP};
		maxT ->
		    {ok, ApplData#appl_data.maxT};
		_ -> undefined
	    end;
	_ ->
	    undefined
    end.
	    
get_pid_all_key(Master) ->
    case ets:match(ac_tab, {{application_master, '$1'}, Master}) of
	[[AppName]] -> get_all_key(AppName);
	_ -> []
    end.

get_all_key(AppName) ->
    case ets:lookup(ac_tab, {loaded, AppName}) of
	[{_, {appl, AppName, ApplData, Desc, Id, Vsn, ResType, IncApps, Apps}}] ->
	    Env = case get_all_env(AppName) of
		      {ok, E} ->
			  E;
		      Else ->
			  Else
		  end,
	    {ok, [{description, Desc}, 
		  {id, Id}, 
		  {vsn, Vsn}, 
		  {modules, ApplData#appl_data.mods}, 
		  {maxP, ApplData#appl_data.maxP}, 
		  {maxT, ApplData#appl_data.maxT}, 
		  {registered, ApplData#appl_data.regs}, 
		  {included_applications, IncApps}, 
		  {applications, Apps}, 
		  {env, Env}, 
		  {mod, ApplData#appl_data.mod}, 
		  {start_phases, ApplData#appl_data.phases}]};
	_ -> 
	    undefined
    end.


start_type(Master) ->
    case ets:match(ac_tab, {{application_master, '$1'}, Master}) of
	[[AppName]] -> 
	    gen_server:call(?AC, {start_type, AppName}, infinity);
	X -> 
	    undefined
    end.






get_master(AppName) ->
    case ets:lookup(ac_tab, {application_master, AppName}) of
	[{_, Pid}] -> Pid;
	_ -> undefined
    end.

get_application(Master) ->
    case ets:match(ac_tab, {{application_master, '$1'}, Master}) of
	[[AppName]] -> {ok, AppName};
	_ -> undefined
    end.

get_application_module(Module) ->
    M = ets:match(ac_tab, {{loaded, '$1'}, ?wild_mods}),
    catch begin foreach(fun([AppName, Mods]) ->
				case lists:member(Module, Mods) of
				    true -> throw({ok, AppName});
				    false -> undefined
				end
			end, M),
		undefined
	  end.

permit_application(ApplName, Flag) ->
    gen_server:call(?AC, 
		    {permit_application, ApplName, Flag},
		    infinity).


%%-----------------------------------------------------------------
%% Undocumented function, used only for test purposes.
%%-----------------------------------------------------------------
set_env(AppName, Key, Val) ->
    gen_server:call(?AC, {set_env, AppName, Key, Val}).

%%%-----------------------------------------------------------------
%%% call-back functions from gen_server
%%%-----------------------------------------------------------------
init(Kernel) ->
    process_flag(trap_exit, true),
    case catch check_conf() of
	{ok, ConfData} ->
	    %% Actually, we don't need this info in an ets table anymore.
	    %% This table was introduced because starting applications
	    %% should be able to get som info from AC (e.g. loaded_apps).
	    %% The new implementation makes sure the AC process can be
	    %% called during start-up of any app.
	    case check_conf_data(ConfData) of
		ok ->
		    ets:new(ac_tab, [set, public, named_table]),
		    S = #state{conf_data = ConfData},
		    {ok, KAppl} = make_appl(Kernel),
		    case catch load(S, KAppl) of
			{'EXIT', LoadError} ->
			    {stop, {'load error', LoadError}};
			{ok, News} ->
			    {ok, News}
		    end;
		{error, ErrorMsg} ->
		    Str = "invalid configuration file",
		    Str2 = lists:flatten(io_lib:format("~s; ~s ~n",
						       [Str, ErrorMsg])),
		    error_logger:format(Str2, []),
		    {stop, {'invalid configuration file', list_to_atom(ErrorMsg), ConfData}}
	    end;
	{error, R} ->
	    {stop, R}
    end.


%% Check the syntax of the .config file  [{ApplicationName, [{Parameter, Value}]}].
check_conf_data([]) ->
    ok;
check_conf_data(ConfData) when list(ConfData) ->
    [Application | ConfDataRem] = ConfData,
    case Application of
	{kernel, List} when list(List) ->
	    case check_para_kernel(List) of
		ok ->
		    check_conf_data(ConfDataRem);
		Error1 ->
		    Error1
	    end;
	{AppName, List} when atom(AppName), list(List) ->
	    case check_para(List, atom_to_list(AppName)) of
		ok ->
		    check_conf_data(ConfDataRem);
		Error2 ->
		    Error2
	    end;
	{AppName, List} when list(List)  ->
	    ErrMsg = "application: "
		++ lists:flatten(io_lib:format("~p",[AppName]))
		++ "; application name must be an atom",
	    {error, ErrMsg};
	{AppName, List} ->
	    ErrMsg = "application: "
		++ lists:flatten(io_lib:format("~p",[AppName]))
		++ "; parameters must be a list",
	    {error, ErrMsg};
	Else ->
	    ErrMsg = "invalid application name: " ++ 
		lists:flatten(io_lib:format(" ~p",[Else])),
	    {error, ErrMsg}
    end;
check_conf_data(ConfData) ->
    {error, 'configuration must be a list ended by <dot><whitespace>'}.
    

%% Special check of distributed parameter for kernel
check_para_kernel([]) ->
    ok;
check_para_kernel([{distributed, Apps} | ParaList]) when list(Apps) ->
    case check_distributed(Apps) of
	{error, ErrorMsg} ->
	    {error, ErrorMsg};
	_ ->
	    check_para_kernel(ParaList)
    end;
check_para_kernel([{distributed, Apps} | ParaList]) ->
    {error, "application: kernel; erroneous parameter: distributed"};
check_para_kernel([{Para, Val} | ParaList]) when atom(Para) ->
    check_para_kernel(ParaList);
check_para_kernel([{Para, Val} | ParaList]) ->
    {error, "application: kernel; invalid parameter: " ++ 
     lists:flatten(io_lib:format("~p",[Para]))};
check_para_kernel(Else) ->
    {error, "application: kernel; invalid parameter list: " ++ 
     lists:flatten(io_lib:format("~p",[Else]))}.
    

check_distributed([]) ->
    ok;
check_distributed([{App, List} | Apps]) when atom(App), list(List) ->
    check_distributed(Apps);
check_distributed([{App, infinity, List} | Apps]) when atom(App), list(List) ->
    check_distributed(Apps);
check_distributed([{App, Time, List} | Apps]) when atom(App), integer(Time), list(List) ->
    check_distributed(Apps);
check_distributed(Else) ->
    {error, "application: kernel; erroneous parameter: distributed"}.


check_para([], AppName) ->
    ok;
check_para([{Para, Val} | ParaList], AppName) when atom(Para) ->
    check_para(ParaList, AppName);
check_para([{Para, Val} | ParaList], AppName) ->
    {error, "application: " ++ AppName ++ "; invalid parameter: " ++ 
     lists:flatten(io_lib:format("~p",[Para]))};
check_para([Else | ParaList], AppName) ->
    {error, "application: " ++ AppName ++ "; invalid parameter: " ++ 
     lists:flatten(io_lib:format("~p",[Else]))}.
    






handle_call({load_application, Application}, From, S) ->
    case catch do_load_application(Application, S) of
	{ok, NewS} ->
	    AppName = get_appl_name(Application),
	    case cntrl(AppName, S, {ac_load_application_req, AppName}) of
		true ->
		    {noreply, S#state{loading = [{AppName, From} |
						 S#state.loading]}};
		false ->
		    {reply, ok, NewS}
	    end;
	{error, Error} ->
	    {reply, {error, Error}, S};
	{'EXIT',R} -> 
	    {reply, {error, R}, S}
    end;

handle_call({unload_application, AppName}, _From, S) ->
    case keysearch(AppName, 1, S#state.running) of
	{value, _} -> {reply, {error, {running, AppName}}, S};
	false ->
	    case get_loaded(AppName) of
		{true, _} ->
		    NewS = unload(AppName, S),
		    cntrl(AppName, S, {ac_application_unloaded, AppName}),
		    {reply, ok, NewS};
		false ->
		    {reply, {error, {not_loaded, AppName}}, S}
	    end
    end;

handle_call({start_application, AppName, RestartType}, From, S) ->
    #state{running = Running, starting = Starting, start_p_false = SPF, 
	   started = Started, start_req = Start_req} = S,
    %% Check if the application is already starting.
    case lists:keysearch(AppName, 1, Start_req) of
	false ->
	    case catch check_start_cond(AppName, RestartType, Started, Running) of
		{ok, Appl} ->
		    Cntrl = cntrl(AppName, S, {ac_start_application_req, AppName}),
		    Perm = application:get_env(kernel, permissions),
		    case {Cntrl, Perm} of
			{true, _} ->
			    {noreply, S#state{starting = [{AppName, RestartType, normal, From} |
							  Starting]}};
			{false, undefined} ->
			    Pid = spawn_starter(From, Appl, S, normal),
			    {noreply, S#state{starting = [{AppName, RestartType, normal, From} |
							  Starting],
					      start_req = [{AppName, From, Pid} | Start_req]}};
			{false, {ok, Perms}} ->
			    case lists:member({AppName, false}, Perms) of
				false ->
				    Pid = spawn_starter(From, Appl, S, normal),
				    {noreply, S#state{starting = [{AppName, RestartType, normal, From} |
								  Starting],
						      start_req = [{AppName, From, Pid} | Start_req]}};
				true ->
				    SS = S#state{start_p_false = [{AppName, RestartType, normal, From} |
								  SPF]},
				    {reply, ok, SS}
			    end
		    end;
		{error, R} ->
		    {reply, {error, R}, S}
	    end;
	{value, {AppName, FromX, PidX}} ->
	    SS = S#state{start_req = [{AppName, From, PidX} |
				      Start_req]},
	    {noreply, SS}
	    
    end;


handle_call({permit_application, AppName, Bool}, From, S) ->
    Control = S#state.control,
    Starting = S#state.starting,
    SPF = S#state.start_p_false,
    Started = S#state.started,
    Running = S#state.running,
    Start_req = S#state.start_req,
    IsLoaded = get_loaded(AppName),
    IsStarting = lists:keysearch(AppName, 1, Starting),
    IsSPF = lists:keysearch(AppName, 1, SPF),
    IsStarted = lists:keysearch(AppName, 1, Started),
    IsRunning = lists:keysearch(AppName, 1, Running),

    case keysearch(AppName, 1, Control) of
	%%========================
	%% distributed application
	%%========================
	{value, _} ->
%            {reply, distributed_application, S};  %% otp-2729	    
	    case {IsLoaded, IsStarting, IsStarted} of
		%% not loaded
		{false, _, _} ->
		    {reply, {error, {not_loaded, AppName}}, S};
		%% only loaded
		{{true, Appl}, false, false} ->
		    {reply, {error, {not_started, AppName}}, S};
%		%% starting
%		{{true, Appl}, {value, Tuple}, false} ->
%		    {reply, distributed_application, S};
%		%% started but not running
%		{{true, Appl}, _, {value, {AppName, RestartType}}} ->
%		    {reply, distributed_application, S};
%		%% already running (can be a failover/takeover)
		_ ->
		    {reply, distributed_application, S}
	    end;
	%%========================
	%% local application
	%%========================
	false ->
	    case {Bool, IsLoaded, IsStarting, IsSPF, IsStarted, IsRunning} of
		%%------------------------
		%% permit the applicaition
		%%------------------------
		%% already running
		{true, _, _, _, _, {value, Tuple}} ->
		    {reply, ok, S};
		%% not loaded
		{true, false, _, _, _, _} ->
		    {reply, {error, {not_loaded, AppName}}, S};
		%% only loaded
		{true, {true, Appl}, false, false, false, false} ->
		    {reply, {error, {not_started, AppName}}, S};
		%% starting
		{true, {true, Appl}, {value, Tuple}, false, false, false} ->
%		    spawn_starter(From, Appl, S, normal),
%		    {noreply, S};
                    {reply, ok, S}; %% otp-2729
		%% start requested but not started because permit was false
		{true, {true, Appl}, false, {value, Tuple}, false, false} ->
		    {AppName, RestartType, normal, _From} = Tuple,
		    Pid = spawn_starter(From, Appl, S, normal),
		    SS = S#state{starting = [{AppName, RestartType, normal, From} | Starting], 
				 start_p_false = keydelete(AppName, 1, SPF),
				 start_req = [{AppName, From, Pid} | Start_req]},
		    {noreply, SS};
		%% started but not running
		{true, {true, Appl}, _, _, {value, {AppName, RestartType}}, false} ->
		    Pid = spawn_starter(From, Appl, S, normal),
		    SS = S#state{starting = [{AppName, RestartType, normal, From} | Starting], 
				 started = keydelete(AppName, 1, Started),
				 start_req = [{AppName, From, Pid} | Start_req]},
		    {noreply, SS};

		%%==========================
		%% unpermit the applicaition
		%%==========================
		%% running
		{false, _, _, _,  _, {value, {_AppName, Id}}} ->
		    {value, {_AppName2, Type}} = keysearch(AppName, 1, Started),
		    stop_appl(AppName, Id, Type),
		    NRunning = keydelete(AppName, 1, Running),
		    {reply, ok, S#state{running = NRunning}};
		%% not loaded
		{false, false, _, _, _,  _} ->
		    {reply, {error, {not_loaded, AppName}}, S};
		%% not started
		{false, {true, Appl}, false, false, false, false} ->
		    {reply, {error, {not_started, AppName}}, S};
		%% starting
		{false, {true, Appl}, {value, Tuple}, false, false, false} ->
		    {reply, ok, S};
		%% start requested but not started because permit was false
		{false, {true, Appl}, false, {value, Tuple}, false, false} ->
		    SS = S#state{start_p_false = keydelete(AppName, 1, SPF)},
		    {reply, ok, SS};
		%% started but not running
		{false, {true, Appl}, _,  _, {value, Tuple}, false} ->
		    {reply, ok, S}

	    end
    end;





handle_call({stop_application, AppName}, _From, S) ->
    #state{running = Running, started = Started} = S,
    case keysearch(AppName, 1, Running) of
	{value, {_AppName, Id}} ->
	    {value, {_AppName2, Type}} = keysearch(AppName, 1, Started),
	    stop_appl(AppName, Id, Type),
	    NRunning = keydelete(AppName, 1, Running),
	    NStarted = keydelete(AppName, 1, Started),
	    cntrl(AppName, S, {ac_application_stopped, AppName}),
	    {reply, ok, S#state{running = NRunning, started = NStarted}};
	false ->
	    case keysearch(AppName, 1, Started) of
		{value, _} ->
		    NStarted = keydelete(AppName, 1, Started),
		    cntrl(AppName, S, {ac_application_stopped, AppName}),
		    {reply, ok, S#state{started = NStarted}};
		false ->
		    {reply, {error, {not_started, AppName}}, S}
	    end
    end;

handle_call({change_application_data, Applications, ConfData}, _From, S) ->
    Loaded = ets:filter(ac_tab,
			fun([{{loaded, AppName}, Appl}]) ->
				{true, Appl};
			   (_) ->
				false
			end,
			[]),
    case catch do_change_apps(Applications, ConfData, Loaded) of
	{error, R} ->
	    {reply, {error, R}, S};
	{'EXIT', R} ->
	    {reply, {error, R}, S};
	NLoaded ->
	    lists:foreach(fun(Appl) ->
				  ets:insert(ac_tab, {{loaded, Appl#appl.name},
						      Appl})
			  end, NLoaded),
	    {reply, ok, S#state{conf_data = ConfData}}
    end;


handle_call(prep_config_change, _From, S) ->
    RunningApps = S#state.running,
    EnvBefore = lists:reverse(do_prep_config_change(RunningApps)),
    {reply, EnvBefore, S};


handle_call({config_change, EnvBefore}, _From, S) ->
    RunningApps = S#state.running,
    R = do_config_change(RunningApps, EnvBefore),
    {reply, R, S};
 


handle_call(which_applications, _From, S) ->
    Reply = zf(fun({Name, Id}) ->
		       case Id of
			   {distributed, _Node} ->
			       false;
			   _ ->
			       {true, #appl{descr = Descr, vsn = Vsn}} =
				   get_loaded(Name),
			       {true, {Name, Descr, Vsn}}
		       end
	       end, S#state.running),
    {reply, Reply, S};

handle_call({set_env, AppName, Key, Val}, _From, S) ->
    ets:insert(ac_tab, {{env, AppName, Key}, Val}),
    {reply, ok, S};

handle_call({control_application, AppName}, {Pid, _Tag}, S) ->
    Control = S#state.control,
    case keysearch(AppName, 1, Control) of
	false ->
	    link(Pid),
	    {reply, true, S#state{control = [{AppName, Pid} | Control]}};
	{value, _} ->
	    {reply, false, S}
    end;

handle_call({start_type, AppName}, _From, S) ->
    Starting = S#state.starting,
    StartType = case keysearch(AppName, 1, Starting) of
		    false ->
			local;
		    {value, {_AppName, RestartType, Type, _F}} ->
			Type
		end,
    {reply, StartType, S};

handle_call(info, _From, S) ->
    Reply = [{loaded, loaded_applications()},
	     {loading, S#state.loading},
	     {started, S#state.started},
	     {start_p_false, S#state.start_p_false},
	     {running, S#state.running},
	     {starting, S#state.starting}],
    {reply, Reply, S}.

handle_cast({application_started, AppName, Res}, S) ->
    #state{starting = Starting, running = Running, started = Started, start_req = Start_req} = S,
    Start_reqN = reply_to_requester(AppName, Start_req, Res),
    {value, {_AppName, RestartType, _Type, _From}} = keysearch(AppName, 1, Starting),
    case Res of
	{ok, Id} ->
	    case AppName of
		kernel -> check_user();
		_ -> ok
	    end,
	    info_started(AppName, nd(Id)),
	    notify_cntrl_started(AppName, Id, S, ok),
	    NRunning = keyreplaceadd(AppName, 1, Running,{AppName,Id}),
	    NStarted = keyreplaceadd(AppName, 1, Started,{AppName,RestartType}),
	    {noreply, S#state{starting = keydelete(AppName, 1, Starting),
			      running = NRunning,
			      started = NStarted,
			      start_req = Start_reqN}};
	{error, R} when RestartType == temporary ->
	    notify_cntrl_started(AppName, undefined, S, {error, R}),
	    info_exited(AppName, R, RestartType),
	    {noreply, S#state{starting = keydelete(AppName, 1, Starting),
			      start_req = Start_reqN}};
	{error, R} when RestartType == transient ->
	    notify_cntrl_started(AppName, undefined, S, {error, R}),
	    info_exited(AppName, R, RestartType),
	    case R of
		"application exited with reason: normal" ->
		    {noreply, S#state{starting = keydelete(AppName, 1, Starting),
				      start_req = Start_reqN}};
		_ ->
		    {stop, shutdown, S}
	    end;
	{error, R} -> %% permanent
	    notify_cntrl_started(AppName, undefined, S, {error, R}),
	    info_exited(AppName, R, RestartType),
	    {stop, shutdown, S}
    end.

handle_info({ac_load_application_reply, AppName, Res}, S) ->
    case keysearchdelete(AppName, 1, S#state.loading) of
	{value, {_AppName, From}, Loading} ->
	    gen_server:reply(From, Res),
	    case Res of
		ok ->
		    {noreply, S#state{loading = Loading}};
		{error, R} ->
		    NewS = unload(AppName, S),
		    {noreply, NewS#state{loading = Loading}}
	    end;
	false ->
	    {noreply, S}
    end;

handle_info({ac_start_application_reply, AppName, Res}, S) ->
    Start_req = S#state.start_req,
    case keysearch(AppName, 1, Starting = S#state.starting) of
	{value, {_AppName, RestartType, Type, From}} ->
	    case Res of
		start_it ->
		    {true, Appl} = get_loaded(AppName),
		     Pid = spawn_starter(From, Appl, S, Type),
		    {noreply, S#state{start_req = [{AppName, From, Pid} | Start_req]}};
		{started, Node} ->
		    gen_server:cast(?AC, {application_started, AppName,
					  {ok, {distributed, Node}}}),
		    reply(From, ok),
		    {noreply, S};
		not_started ->
		    Started = S#state.started,
		    reply(From, ok),
		    {noreply, 
		     S#state{starting = keydelete(AppName, 1, Starting),
			     started = [{AppName, RestartType} | Started]}};
		{takeover, Node} ->
		    {true, Appl} = get_loaded(AppName),
		    Pid = spawn_starter(From, Appl, S, {takeover, Node}),
		    NewStarting1 = keydelete(AppName, 1, Starting),
		    NewStarting = [{AppName, RestartType, {takeover, Node}, From} | NewStarting1],
		    {noreply, S#state{starting = NewStarting, 
				      start_req = [{AppName, From, Pid} | Start_req]}};
		{error, Reason} when RestartType == permanent ->
		    reply(From, {error, Reason}),
		    {stop, Reason, S};
		{error, Reason} ->
		    reply(From, {error, Reason}),
		    {noreply, S#state{starting =
				      keydelete(AppName, 1, Starting)}}
	    end;
	false ->
	    {noreply, S} % someone called stop before control got that
    end;

handle_info({ac_change_application_req, AppName, Msg}, S) ->
    Running = S#state.running,
    Started = S#state.started,
    Starting = S#state.starting,
    case {keysearch(AppName, 1, Running), keysearch(AppName, 1, Started)} of
	{{value, {AppName, Id}}, {value, {_AppName2, Type}}} ->
	    case Msg of
		{started, Node} ->
		    stop_appl(AppName, Id, Type),
		    NRunning = [{AppName, {distributed, Node}} |
				keydelete(AppName, 1, Running)],
		    {noreply, S#state{running = NRunning}};
		{takeover, Node, _RT} when pid(Id) -> % it is running already
		    notify_cntrl_started(AppName, Id, S, ok),
		    {noreply, S};
		{takeover, Node, RT} ->
		    NewS = do_start(AppName, RT, {takeover, Node}, S),
		    {noreply, NewS};
		{failover, Node, _RT} when pid(Id) -> % it is running already
		    notify_cntrl_started(AppName, Id, S, ok),
		    {noreply, S};
		{failover, Node, RT} ->
		    case application:get_key(AppName, start_phases) of
			{ok, undefined} ->
			    %% to be backwards compatible the application
			    %% is not started as failover if start_phases  
			    %% is not defined in the .app file
			    NewS = do_start(AppName, RT, normal, S),
			    {noreply, NewS};
			{ok, StartPhases} ->
			    NewS = do_start(AppName, RT, {failover, Node}, S),
			    {noreply, NewS}
		    end;
		stop_it ->
		    stop_appl(AppName, Id, Type),
		    cntrl(AppName, S, {ac_application_not_run, AppName}),
		    NRunning = keydelete(AppName, 1, Running),
		    {noreply, S#state{running = NRunning}};
		%% We should not try to start a running application!
		start_it when pid(Id) ->
		    notify_cntrl_started(AppName, Id, S, ok),
		    {noreply, S};
		start_it ->
		    NewS = do_start(AppName, undefined, normal, S),
		    {noreply, NewS};
		not_running ->
		    NRunning = keydelete(AppName, 1, Running),
		    {noreply, S#state{running = NRunning}};
		_ ->
		    {noreply, S}
	    end;
	_ ->
	    IsLoaded = get_loaded(AppName),
	    IsStarting = lists:keysearch(AppName, 1, Starting),
	    IsStarted = lists:keysearch(AppName, 1, Started),
	    IsRunning = lists:keysearch(AppName, 1, Running),

	    case Msg of
		start_it ->
		    case {IsLoaded, IsStarting, IsStarted, IsRunning} of
			%% already running
			{_, _, _, {value, Tuple}} ->
			    {noreply, S};
			%% not loaded
			{false, _, _, _} ->
			    {noreply, S};
			%% only loaded
			{{true, Appl}, false, false, false} ->
			    {noreply, S};
			%% starting
			{{true, Appl}, {value, Tuple}, false, false} ->
			    NewS = do_start(AppName, undefined, normal, S),
			    {noreply, NewS};
			%% started but not running
			{{true, Appl}, _, {value, {AppName, RestartType}}, false} ->
			    NewS = do_start(AppName, undefined, normal, S),
			    SS = NewS#state{started = keydelete(AppName, 1, Started)},
			    {noreply, SS}
		    end;
		{started, Node} ->
		    NRunning = [{AppName, {distributed, Node}} |
				keydelete(AppName, 1, Running)],
		    {noreply, S#state{running = NRunning}};
		_ ->
		    {noreply, S} % someone called stop before control got that
	    end
    end;

%%-----------------------------------------------------------------
%% An application died.  Check its restart_type.  Maybe terminate
%% all other applications.
%%-----------------------------------------------------------------
handle_info({'EXIT', Pid, Reason}, S) ->
    ets:match_delete(ac_tab, {{application_master, '_'}, Pid}),
    NRunning = keydelete(Pid, 2, S#state.running),
    NewS = S#state{running = NRunning},
    case keysearch(Pid, 2, S#state.running) of
	{value, {AppName, _AmPid}} ->
	    cntrl(AppName, S, {ac_application_stopped, AppName}),
	    case keysearch(AppName, 1, S#state.started) of
		{value, {_AppName, temporary}} ->
		    info_exited(AppName, Reason, temporary),
		    {noreply, NewS};
		{value, {_AppName, transient}} when Reason == normal ->
		    info_exited(AppName, Reason, transient),
		    {noreply, NewS};
		{value, {_AppName, Type}} ->
		    info_exited(AppName, Reason, Type),
		    {stop, shutdown, NewS}
	    end;
	false ->
	    {noreply, S#state{control = del_cntrl(S#state.control, Pid)}}
    end;
    
handle_info(_, S) ->
    {noreply, S}.

terminate(Reason, S) ->
    foreach(fun({_AppName, Id}) when pid(Id) -> 
		    exit(Id, shutdown),
		    receive
			{'EXIT', Id, _} -> ok
		    end;
	       (_) -> ok
	    end,
	    S#state.running),
    ets:delete(ac_tab).

%%%-----------------------------------------------------------------
%%% Internal functions
%%%-----------------------------------------------------------------
cntrl(AppName, #state{control = Control}, Msg) ->
    case keysearch(AppName, 1, Control) of
	{value, {_AppName, Pid}} ->
	    Pid ! Msg,
	    true;
	false -> 
	    false
    end.

notify_cntrl_started(AppName, {distributed, Node}, S, _Res) ->
    ok;
notify_cntrl_started(AppName, Id, S, Res) ->
    cntrl(AppName, S, {ac_application_run, AppName, Res}).
    
del_cntrl([{_, Pid}|T], Pid) ->
    del_cntrl(T, Pid);
del_cntrl([H|T], Pid) ->
    [H|del_cntrl(T, Pid)];
del_cntrl([], Pid) ->
    [].

get_loaded(App) ->
    AppName = get_appl_name(App),
    case ets:lookup(ac_tab, {loaded, AppName}) of 
	[{_Key, Appl}] -> {true, Appl};
	_  -> false
    end.
    
do_load_application(Application, S) ->
    case get_loaded(Application) of
	{true, _} ->
	    throw({error, {already_loaded, Application}});
	false ->
	    case make_appl(Application) of
		{ok, Appl} -> load(S, Appl);
		Error -> Error
	    end
    end.

%% Recursively load the application and its included apps.
%load(S, {ApplData, ApplEnv, IncApps, Descr, Vsn, Apps}) ->
load(S, {ApplData, ApplEnv, IncApps, Descr, Id, Vsn, Apps}) ->
    Name = ApplData#appl_data.name,
    ConfEnv = get_env_i(Name, S),
    NewEnv = merge_app_env(ApplEnv, ConfEnv),
    CmdLineEnv = get_cmd_env(Name),
    NewEnv2 = merge_app_env(NewEnv, CmdLineEnv),
    NewEnv3 = keyreplaceadd(included_applications, 1, NewEnv2,
			    {included_applications, IncApps}),
    add_env(Name, NewEnv3),
    Appl = #appl{name = Name, descr = Descr, id = Id, vsn = Vsn, 
		 appl_data = ApplData, inc_apps = IncApps, apps = Apps},
    ets:insert(ac_tab, {{loaded, Name}, Appl}),
    NewS =
	foldl(fun(App, S1) ->
		      case get_loaded(App) of
			  {true, _} -> S1;
			  false ->
			      case do_load_application(App, S1) of
				  {ok, S2} -> S2;
				  Error -> throw(Error)
			      end
		      end
	      end, S, IncApps),
    {ok, NewS}.

unload(AppName, S) ->
    {ok, IncApps} = get_env(AppName, included_applications),
    del_env(AppName),
    Loaded = ets:delete(ac_tab, {loaded, AppName}),
    foldl(fun(App, S1) ->
		  case get_loaded(App) of
		      false -> S1;
		      {true, _} -> unload(App, S1)
		  end
	  end, S, IncApps).

	    
check_start_cond(AppName, RestartType, Started, Running) ->
    validRestartType(RestartType),
    case get_loaded(AppName) of
	{true, Appl} ->
	    %% Check Running; not Started.  An exited app is not running,
	    %% but started.  It must be possible to start an exited app!
	    case keysearch(AppName, 1, Running) of
		{value, _} ->
		    {error, {already_started, AppName}};
		_ ->
		    foreach(
		      fun(AppName2) ->
			      case keysearch(AppName2, 1, Started) of
				  {value, _} -> ok;
				  _ -> throw({error, {not_started, AppName2}})
			      end
		      end, Appl#appl.apps),
		    {ok, Appl}
	    end;
	false ->
	    {error, {not_loaded, AppName}}
    end.


do_start(AppName, RT, Type, S) ->
    case keysearch(AppName, 1, S#state.started) of
	{value, {_AppName2, OldRT}} ->
	    case keysearch(AppName, 1, S#state.starting) of
		false ->
		    RestartType = get_restart_type(RT, OldRT),
		    {true, Appl} = get_loaded(AppName),
		    spawn_starter(undefined, Appl, S, Type),
		    Starting = [{AppName, RestartType, Type, undefined} | 
				S#state.starting],
		    S#state{starting = Starting};
		{value, _} -> % otherwise we're already starting the app...
		    S
	    end;
	false ->
	    S
    end.
    
spawn_starter(From, Appl, S, Type) ->
    spawn_link(?MODULE, init_starter, [From, Appl, S, Type]).

init_starter(From, Appl, S, Type) ->
    process_flag(trap_exit, true),
    AppName = Appl#appl.name,
    case catch start_appl(Appl, S, Type) of
	{ok, Id} ->
%	    reply(From, ok),
	    gen_server:cast(?AC, {application_started, AppName, {ok, Id}});
	{info, R}  ->
%	    reply(From, {error, R}),
	    gen_server:cast(?AC, {application_started, AppName,
				  {error, no_report}});
	{error, R}  ->
%	    reply(From, {error, R}),
	    gen_server:cast(?AC, {application_started, AppName, {error, R}})
    end.

reply(undefined, _Reply) -> 
    ok;
reply(From, Reply) -> gen_server:reply(From, Reply).

start_appl(Appl, S, Type) ->
    ApplData = Appl#appl.appl_data,
    case ApplData#appl_data.mod of
	[] ->
	    {ok, undefined};
	_ ->
	    Name = ApplData#appl_data.name,
	    Running = S#state.running,
	    foreach(
	      fun(AppName) ->
		      case keysearch(AppName, 1, Running) of
			  {value, _} ->
			      ok;
			  _ ->
			      throw({info, {not_running, AppName}})
		      end
	      end, Appl#appl.apps),
	    case application_master:start_link(ApplData, Type) of
		{ok, Pid} ->
		    {ok, Pid};
		{error, Reason} ->
		    throw({error, Reason})
	    end
    end.

    
%%-----------------------------------------------------------------
%% Stop application locally.
%%-----------------------------------------------------------------
stop_appl(AppName, Id, Type) when pid(Id) ->
    unlink(Id),
    application_master:stop(Id),
    info_exited(AppName, stopped, Type),
    ets:delete(ac_tab, {application_master, AppName});
stop_appl(AppName, undefined, Type) ->
    %% Code-only application stopped
    info_exited(AppName, stopped, Type);
stop_appl(AppName, _Id, Type) ->
    %% Distributed application stopped
    ok. 

keysearchdelete(Key, Pos, List) ->
    ksd(Key, Pos, List, []).

ksd(Key, Pos, [H | T], Rest) when element(Pos, H) == Key ->
    {value, H, Rest ++ T};
ksd(Key, Pos, [H | T], Rest) ->
    ksd(Key, Pos, T, [H | Rest]);
ksd(_Key, _Pos, [], _Rest) ->
    false.
    
keyreplaceadd(Key, Pos, List, New) ->
    %% Maintains the order!
    case keysearch(Key, Pos, List) of
	{value, _} -> keyreplace(Key, Pos, List, New);
	_ -> [New | List]
    end.

validRestartType(permanent)   -> true;
validRestartType(temporary)   -> true;
validRestartType(transient)   -> true;
validRestartType(RestartType) ->
    throw({error, {invalid_restart_type, RestartType}}).

nd({distributed, Node}) -> Node;
nd(_) -> node().
	  
get_restart_type(undefined, OldRT) ->
    OldRT;
get_restart_type(RT, _OldRT) ->
    RT.

get_appl_name(Name) when atom(Name) -> Name;
get_appl_name({application, Name, _}) when atom(Name) -> Name;
get_appl_name(Appl) -> throw({error, {bad_application, Appl}}).

make_appl(Name) when atom(Name) ->
    FName = atom_to_list(Name) ++ ".app",
    case file:path_consult(code:get_path(), FName) of
	{ok, [Application], _} -> {ok, make_appl_i(Application)};
	{error, Reason} -> {error, {file:format_error(Reason), FName}}
    end;
make_appl(Application) ->
    {ok, make_appl_i(Application)}.

make_appl_i({application, Name, Opts})
  when atom(Name), list(Opts) ->
    Descr = get_opt(description, Opts, ""),
    Id = get_opt(id, Opts, ""),
    Vsn = get_opt(vsn, Opts, ""),
    Mods = get_opt(modules, Opts, []),
    Regs = get_opt(registered, Opts, []),
    Apps = get_opt(applications, Opts, []),
    Mod =
	case get_opt(mod, Opts, []) of
	    {M,A} when atom(M) -> {M,A};
	    [] -> [];
	    Other -> throw({error, {badstartspec, Other}})
	end,
    Phases = get_opt(start_phases, Opts, undefined),
%    Phases = [],
    Env = get_opt(env, Opts, []),
    MaxP = get_opt(maxP, Opts, infinity),
    MaxT = get_opt(maxT, Opts, infinity),
    IncApps = get_opt(included_applications, Opts, []),
%    {#appl_data{name = Name, regs = Regs, mod = Mod,  mods = Mods,
%		maxP = MaxP, maxT = MaxT},
%     Env, IncApps, Descr, Vsn, Apps};
    {#appl_data{name = Name, regs = Regs, mod = Mod, phases = Phases, mods = Mods,
		inc_apps = IncApps, maxP = MaxP, maxT = MaxT},
     Env, IncApps, Descr, Id, Vsn, Apps};
make_appl_i({application, Name, Opts}) when list(Opts) ->
    throw({error,{invalid_name,Name}});
make_appl_i({application, Name, Opts}) ->
    throw({error,{invalid_options, Opts}});
make_appl_i(Appl) -> throw({error, {bad_application, Appl}}).


%%-----------------------------------------------------------------
%% Merge current applications with changes.  
%%-----------------------------------------------------------------
do_change_apps(Applications, ConfData, Apps) ->
    map(fun(Appl) ->
		Name = Appl#appl.name,
		case get_new_appl(Name, Applications) of
		    {ok, Application} ->
			do_change_appl(make_appl(Application),
				       Appl, ConfData);
		    false ->
			Appl
		end
	end, Apps).

do_change_appl({ok, {ApplData, ApplEnv, IncApps, Descr, Id, Vsn, Apps2}},
	       Appl, ConfData) ->
    Name = Appl#appl.name,
    ConfEnv = get_opt(Name, ConfData, []),
    NewEnv = merge_app_env(ApplEnv, ConfEnv),
    CmdLineEnv = get_cmd_env(Name),
    NewEnv2 = merge_app_env(NewEnv, CmdLineEnv),
    NewEnv3 = keyreplaceadd(included_applications, 1, NewEnv2,
			    {included_applications, IncApps}),
    change_appl(Appl, NewEnv3, Vsn, Descr, Apps2);
do_change_appl({error, R}, _Appl, _ConfData) ->
    throw({error, R}).

get_opt(Key, List, Default) ->
    case keysearch(Key, 1, List) of
	{value, {_Key, Val}} -> Val;
	_ -> Default
    end.

get_cmd_env(Name) ->
    case init:get_argument(Name) of
	{ok, Args} ->
	   foldl(fun(List, Res) -> conv(List) ++ Res end, [], Args);
	_ -> []
    end.

conv([Key, Val | T]) ->
    case make_term(Key) of
	{ok, K} ->
	    case make_term(Val) of
		{ok, V} -> [{K, V} | conv(T)];
		_ -> conv(T)
	    end;
	_ -> conv(T)
    end;
conv(_) -> [].

%%% Fix some day: eliminate the duplicated code here
make_term(Str) -> 
    case erl_scan:string(Str) of
	{ok, Tokens, _} ->		  
	    case erl_parse:parse_term(Tokens ++ [{dot, 1}]) of
		{ok, Term} ->
		    {ok, Term};
		{error, {_,M,Reason}} ->
		    error_logger:format("application_controller: ~s: ~s~n",
					[M:format_error(Reason), Str]),
		    throw({error, {bad_environment_value, Str}})
	    end;
	{error, {_,M,Reason}, _} ->
	    error_logger:format("application_controller: ~s: ~s~n",
				[M:format_error(Reason), Str]),
	    throw({error, {bad_environment_value, Str}})
    end.

get_env_i(Name, #state{conf_data = ConfData}) when list(ConfData) ->
    case keysearch(Name, 1, ConfData) of
	{value, {_Name, Env}} -> Env;
	_ -> []
    end;
get_env_i(_Name, _) -> [].

%% Merges envs for all apps.  Env2 overrides Env1
merge_env(Env1, Env2) ->
    merge_env(Env1, Env2, []).

merge_env([{App, AppEnv1} | T], Env2, Res) ->
    case get_env_key(App, Env2) of
	{value, AppEnv2, RestEnv2} ->
	    NewAppEnv = merge_app_env(AppEnv1, AppEnv2),
	    merge_env(T, RestEnv2, [{App, NewAppEnv} | Res]);
	_ ->
	    merge_env(T, Env2, [{App, AppEnv1} | Res])
    end;
merge_env([], Env2, Res) ->
    Env2 ++ Res.

    

%% Merges envs for an application.  Env2 overrides Env1
merge_app_env(Env1, Env2) ->
    merge_app_env(Env1, Env2, []).

merge_app_env([{Key, Val} | T], Env2, Res) ->
    case get_env_key(Key, Env2) of
	{value, NewVal, RestEnv} ->
	    merge_app_env(T, RestEnv, [{Key, NewVal}|Res]);
	_ ->
	    merge_app_env(T, Env2, [{Key, Val} | Res])
    end;
merge_app_env([], Env2, Res) ->
    Env2 ++ Res.

get_env_key(Key, Env) -> get_env_key(Env, Key, []).
get_env_key([{Key, Val} | T], Key, Res) ->
    {value, Val, T ++ Res};
get_env_key([H | T], Key, Res) ->
    get_env_key(T, Key, [H | Res]);
get_env_key([], _Key, Res) -> Res.

add_env(Name, Env) ->
    foreach(fun({Key, Value}) ->
			  ets:insert(ac_tab, {{env, Name, Key}, Value})
		  end,
		  Env).

del_env(Name) ->
    ets:match_delete(ac_tab, {{env, Name, '_'}, '_'}).

check_user() ->
    case whereis(user) of
	User when pid(User) -> group_leader(User, self());
	_ -> ok
    end.


%%-----------------------------------------------------------------
%% Prepare for a release upgrade by reading all the evironment variables.
%%-----------------------------------------------------------------
do_prep_config_change(Apps) ->
    do_prep_config_change(Apps, []).

do_prep_config_change([], EnvBefore) ->
    EnvBefore;
do_prep_config_change([{App, Id} | Apps], EnvBefore) ->
    Env = application:get_all_env(App),
    do_prep_config_change(Apps, [{App, Env} | EnvBefore]).
    


%%-----------------------------------------------------------------
%% Inform all running applications about the changed configuration.
%%-----------------------------------------------------------------
do_config_change(Apps, EnvBefore) ->
    do_config_change(Apps, EnvBefore, []).

do_config_change([], EnvBefore, []) ->
    ok;
do_config_change([], EnvBefore, Errors) ->
    {error, Errors};
do_config_change([{App, Id} | Apps], EnvBefore, Errors) ->
    AppEnvNow = lists:sort(application:get_all_env(App)),
    AppEnvBefore = case lists:keysearch(App, 1, EnvBefore) of
		       false ->
			   [];
		       {value, {App, AppEnvBeforeT}} ->
			   lists:sort(AppEnvBeforeT)
		   end,

    Res = 
	case AppEnvNow of
	    AppEnvBefore ->
		ok;
	    _ ->
		case do_config_diff(AppEnvNow, AppEnvBefore) of
		    {[], [], []} ->
			ok;
		    {Changed, New, Removed} ->
			case application:get_key(App, mod) of
			    {ok, {Mod, Para}} ->
				case catch Mod:config_change(Changed, New, 
							     Removed) of
				    ok ->
					ok;
				    %% It is not considered as an error
				    %% if the cb-function is not defined 
				    {'EXIT', {undef, _}} ->
					ok;
				    {error, Error} ->
					{error, Error};
				    Else ->
					{error, Else}
				end;
			    {ok,[]} ->
				{error, {module_not_defined, App}};
			    undefined ->
				{error, {application_not_found, App}}
			end
		end
	end,
    
    case Res of
	ok ->
	    do_config_change(Apps, EnvBefore, Errors);
	{error, NewError} ->
	    do_config_change(Apps, EnvBefore,[NewError | Errors])
    end.
	    
	    
   

%%-----------------------------------------------------------------
%% Check if the configuration is changed in anyway.
%%-----------------------------------------------------------------
do_config_diff(AppEnvNow, AppEnvBefore) ->
    do_config_diff(AppEnvNow, AppEnvBefore, {[], []}).

do_config_diff([], AppEnvBefore, {Changed, New}) ->
    Removed = lists:foldl(fun({Env, Value}, Acc) -> [Env | Acc] end, [], AppEnvBefore),
    {Changed, New, Removed};
do_config_diff(AppEnvNow, [], {Changed, New}) ->
    {Changed, AppEnvNow++New, []};
do_config_diff([{Env, Value} | AppEnvNow], AppEnvBefore, {Changed, New}) ->
    case lists:keysearch(Env, 1, AppEnvBefore) of
	{value, {Env, Value}} ->
	    do_config_diff(AppEnvNow, lists:keydelete(Env,1,AppEnvBefore), {Changed, New});
	{value, {Env, OtherValue}} ->
	    do_config_diff(AppEnvNow, lists:keydelete(Env,1,AppEnvBefore), 
			   {[{Env, Value} | Changed], New});
	false ->
	    do_config_diff(AppEnvNow, AppEnvBefore, {Changed, [{Env, Value}|New]})
    end.
    



    

%%-----------------------------------------------------------------
%% Read the .config files.
%%-----------------------------------------------------------------
check_conf() ->
    case init:get_argument(config) of
	{ok, Files} ->
	    {ok, lists:foldl(
		   fun([File], Env) ->
			   BFName = filename:basename(File,".config"),
			   FName = filename:join(filename:dirname(File),
						 BFName ++ ".config"),
			   case load_file(FName) of
			       {ok, NewEnv} ->
				   merge_env(Env, NewEnv);
			       {error, {Line, _Mod, Str}} ->
				   Str2 = lists:flatten(
					    io_lib:format("~p: ~w: ~s~n",
							  [FName,Line,Str])),
				   error_logger:format(Str2, []),
				   throw({error, config_error})
			   end
		   end, [], Files)};
	_ -> {ok, []}
    end.
	    
load_file(File) ->
    case erl_prim_loader:get_file(File) of
	{ok, Bin, _FileName} ->
	    Str = binary_to_list(Bin),
	    case erl_scan:tokens([], Str, 1) of
		{done, {ok, Tokens, _}, _} ->
		    [First| T] = Tokens,
		    L = length(Tokens),
		    Last = lists:nth(L-1, Tokens),
		    case {First, Last} of
			{{'[',_},{']',_}} ->
			    erl_parse:parse_term(Tokens);
			_ -> 
			    {error, {none, load_file, 
				     "configuration file must be a list ended "
				     "by <dot><whitespace>"}}
		    end;
		{done, Result, _} ->
		    {error, {none, parse_file, tuple_to_list(Result)}};
		{more, _} ->
		    {error, {none, load_file, "<dot><whitespace> not found"}}
	    end;
	error ->
	    {error, {none, open_file, "configuration file not found"}}
    end.

get_new_appl(Name, [{application, Name, App} | _]) ->
    {ok, {application, Name, App}};
get_new_appl(Name, [_ | T]) -> get_new_appl(Name, T);
get_new_appl(Name, []) -> false.

change_appl(Appl, Env, Vsn, Descr, Apps) ->
    ApplData = Appl#appl.appl_data,
    if
	Env /= [] ->
	    del_env(Appl#appl.name),
	    add_env(Appl#appl.name, Env);
	true -> ok
    end,
    Appl#appl{vsn = Vsn, descr = Descr, apps = Apps}.

%%-----------------------------------------------------------------
%% Info messages sent to error_logger
%%-----------------------------------------------------------------
info_started(Name, Node) ->
    Rep = [{application, Name},
	   {started_at, Node}],
    error_logger:info_report(progress, Rep).

info_exited(Name, no_report, Type) ->
    ok;
info_exited(Name, Reason, Type) ->
    Rep = [{application, Name},
	   {exited, Reason},
	   {type, Type}],
    error_logger:info_report(Rep).


%%-----------------------------------------------------------------
%% Reply to all processes waiting this application to be started.  
%%-----------------------------------------------------------------
reply_to_requester(AppName, Start_req, Res) ->
    R = case Res of
	    {ok, Id} ->
		ok;
	    Error ->
		Error
	end,

    lists:foldl(fun(Sp, AccIn) ->
			case Sp of
			    {AppName, From, Pid} ->
				reply(From, R),
				AccIn;
			    _ ->
				[Sp | AccIn]
			end
		end,
		[],
		Start_req).
    



%%-----------------------------------------------------------------
%% These functions are only to be used from testsuites.  
%%-----------------------------------------------------------------
test_change_apps(Apps, Conf) ->
    Res = test_make_apps(Apps, []),
    test_do_change_appl(Apps, Conf, Res).

test_do_change_appl([], _, _) ->
    ok;
test_do_change_appl([A|Apps], [], [R|Res]) ->
    do_change_appl(R, #appl{name = A}, []),
    test_do_change_appl(Apps, [], Res);
test_do_change_appl([A|Apps], [C|Conf], [R|Res]) ->
    do_change_appl(R, #appl{name = A}, C),
    test_do_change_appl(Apps, Conf, Res).



test_make_apps([], Res) ->
    lists:reverse(Res);
test_make_apps([A|Apps], Res) ->
    test_make_apps(Apps, [make_appl(A) | Res]).



