#!/bin/sh -fvx

Cmds="\
Res = (catch begin
SrcDir = \"src\", \
OutDir = \"ebin\", \
AppName = \"ccviewer\", \
Id = \"ccviewer\", \
\
{ok, Cwd} = file:get_cwd(), \
DirParts = filename:split(Cwd), \
[Parent | _] = lists:reverse(DirParts), \
{ok, [_, Vsn]} = regexp:split(Parent, \"-\"), \
\
AppNameA = list_to_atom(AppName), \
{ok, Beams} = file:list_dir(OutDir), \
Mods = lists:foldl(fun(F,Acc) -> \
  case regexp:gsub(F,\".beam\",\"\") of \
    {ok,M,N} when N>0 -> \
      [list_to_atom(M)|Acc]; \
     _ -> \
      Acc \
  end \
end, [], Beams), \
AppSrc = filename:join(SrcDir, AppName ++ \".appSrc\"), \
{ok, [{application,AppNameA,Opts}]} = file:consult(AppSrc) \
end).
case Res of {'EXIT', Reason} -> erlang:halt(); _ -> ok end.
Opts1 = lists:keyreplace(modules, 1, Opts, {modules, Mods}). \
Opts2 = lists:keyreplace(id, 1, Opts1, {id, Id}). \
Opts3 = lists:keyreplace(vsn, 1, Opts2, {vsn, Vsn}). \
{ok, Fd} = file:open(filename:join(OutDir, AppName ++ \".app\"), [write]). \
io:format(Fd, \"~p.~n\", [{application, AppNameA, Opts3}]). \
file:close(Fd). "

echo "$Cmds" | erl -boot start_clean
