%%% Part 4 - Standalone application generation %%%

:- use_module(library(system),[system/1,environ/2]).

% A few simple support predicates to make standalone cgi-bin applications
save_cgi_bin(Name,EntryPoint) :-
        cgi_bin_dir(BinDir),
        atom_concat(BinDir,Name,FullName),
        save(FullName,Return),
        boot_form(Return,FullName,EntryPoint).

boot_form(0,FullName,_) :- 
        atom_concat('chmod ugo+rx ',FullName,Command),
        system(Command).

boot_form(1,_,EntryPoint) :- 
        html_protect(EntryPoint),
        halt.

html_protect(Goal) :-
        on_exception(E,Goal,html_report_error(E)).
html_protect(_) :-
        html_report_error('Sorry, html_pl application failed.').

%%% Support predicates %%%

%% Concatenates two atoms
atom_concat(A,B,AB) :-
        name(A,AS),
        name(B,BS),
        append(AS,BS,ABS),
        name(AB,ABS).

append([],X,X).
append([H|T1],L,[H|T2]) :- append(T1,L,T2).

%% Get Unix environment variable
getenv(Var,Val) :- environ(Var,Val).

