%% This library contains functions aiming at simplifying the development of
%% EMakefiles
-module(ermake_lib).

-author("mickael.remond@erlang-fr.org").

-export([subst/3]).


%% This function aims at replacing simple and direct substitution traditionaly
%% done with SED in Unix makefile
%% Take the name of an Input file and output file.
%% It is usefull when you have template (for example starting scripts)
%% that need some substitution during the build of the project.
%% Substitution are expressed as a list of tuples of the form {"Regexp", "Replacement string"}

%% Load file, perform substitution, save new file
subst(InFile, OutFile, ListOfSubsts) ->
    %% Read the file as a binary.
    {ok, Bin} = file:read_file(InFile),
    String = binary_to_list(Bin),
    NewString = perform_all_substs(String, ListOfSubsts),
    NewBin = list_to_binary(NewString),
    file:write_file(OutFile, NewBin).

perform_all_substs(String, []) ->
    String;
perform_all_substs(String, [Subst|Substs]) ->
    {Regexp, NewStr} = Subst,
    case regexp:gsub(String, Regexp, NewStr) of
	{ok, NewString, RepCount} ->
	    perform_all_substs(NewString, Substs);
	{error, Error} ->
	    io:format("Error in Regexp: ~p~n", [Error]),
	    perform_all_substs(String, Substs)
    end.

%% Clean is intended to be use as a way to remove list of target
%% resulting from previous project build.
%% It get a string, which is a comma separated list of file to remove.
%% Space, tabulation and carriage return are remove from the string.
%% Then the string is split based on the comma file delimiter.
%% Each file from the resulting list of file is then deleted.
%% It makes easy to write a clean target in EMakefile, thus making easier
%% to clean-up your directory structure before release your source code.
%clean(String) ->
    %% Remove unwanted characters:
