#!/usr/bin/env escript
%% -*- erlang -*-



-mode(compile).
-define(NOT_IN_GIT_ERR_MSG,
    "ERROR: To build outside a git work tree, you must first create
           a versioned archive, and then unpack it and build that.
           This is for the version number to get correctly set.
           Use helpers/mk-versioned-archive to create such an archive.

           The helpers/mk-versioned-archive can be used from a git worktree
           or from eg Github's automatically generated tar/zip files
           or similar. If you use it from a (non-shallow) git work tree
           with tags intact, the version will get picked up automatically,
           otherwise you must know the proper version and specify it manually,
           see mk-versioned-archive --help for further assistance.

           For further info, see the README.md, the section section
           named Building outside of a git work tree.").

file_err(FunName, FileName, Reason) ->
    io:format(standard_error, "file:~p(~s) excute failed!, Reason :~s ~n",
        [FunName, FileName, file:format_error(Reason)]),
    halt(1).


main([InFile, OutFile]) ->
    InGit = os:cmd("git rev-parse --is-inside-work-tree  2>&1"),
    case InGit of
        "true" ++ _ ->
            next;
        _ ->
            io:format(standard_error, "~s~n", [?NOT_IN_GIT_ERR_MSG]),
            halt(1)
    end,
    Vsn0 = os:cmd("git describe --always --tags --match [0-9]*.[0-9]*"),
    Vsn = lists:sublist(Vsn0, length(Vsn0) - 1),
    BaseStr = case file:read_file(InFile) of
                  {ok, S} ->
                      S;
                  {error, Reason} ->
                      file_err(read_file, InFile, Reason)
              end,
    SedList =
        [
            {<<"@vsn@">>, Vsn},
            {<<"is expected to be">>, <<"was">>},
            {<<"%% The version below">>, [<<"%% DO NOT EDIT -- generated ">>,
                <<"from gpb_version.hrl.in\n%% The version below">>]},
            {<<"%% NB: The build.mk_version_hrl depends.*">>, <<"">>}
        ],
    VersionStr = lists:foldl(fun({Patten, Replacement}, Acc) ->
        re:replace(Acc, Patten, Replacement, [{return, binary}])
                             end, BaseStr, SedList),
    case file:write_file(OutFile, VersionStr) of
        ok ->
            ok;
        {error, Reason2} ->
            file_err(write_file, OutFile, Reason2)
    end.
