
% uses app_config/2 which you're responsible for setting up first.

:- dynamic cmd_line_debug/0.
:- dynamic cmd_line_daemon/0.
:- dynamic cmd_line_xpce/0.

:- ensure_loaded(library(debug)).
% :- debug(argv).

handle_argv :-
	current_prolog_flag(argv, Argv),
        (  append(_, [--|Args], Argv)
	->  debug(argv, 'Args: ~q', [Args]),
	    consume_argv(Args),
	    debug(argv, 'Args consumed.', []),
	   !
	;  true
	).

consume_argv([]).
consume_argv([DashDashConfigOption, NewValue | Tail]) :-
	atom_concat('--', ConfigOption, DashDashConfigOption),
	retract(app_config(ConfigOption, OldValue)),
	assert(app_config(ConfigOption, NewValue)),
	debug(argv, 'Config override, ~a changed from ~q to ~q',
	      [ConfigOption, OldValue, NewValue]),
	consume_argv(Tail).
consume_argv(['--daemon' | Tail]) :-
 	assert(cmd_line_daemon),
	consume_argv(Tail).
consume_argv(['--xpce' | Tail]) :-
	assert(cmd_line_xpce),
	consume_argv(Tail).
consume_argv(['--debug' | Tail]) :-
	assert(cmd_line_debug),
	consume_argv(Tail).
consume_argv(['--ensure_loaded', FileName| Tail]) :-
	ensure_loaded(FileName),
	consume_argv(Tail).
consume_argv(['--www-override', WWW_Dir | Tail]) :-
	assert(app_config(www_override, WWW_Dir)),
	consume_argv(Tail).
consume_argv(['-d' | Tail]) :-
	assert(cmd_line_debug),
	consume_argv(Tail).
consume_argv([Error | Tail]) :-
	print_message(error, format('unknown option ignored: ~q~n', Error)),
	consume_argv(Tail).

