#!/usr/bin/env escript

%%% Build escript(s) to be included with an eturnal release.
%%%
%%% Copyright (c) 2022 Holger Weiss <holger@zedat.fu-berlin.de>.
%%% Copyright (c) 2022 ProcessOne, SARL.
%%% All rights reserved.
%%%
%%% Licensed under the Apache License, Version 2.0 (the "License");
%%% you may not use this file except in compliance with the License.
%%% You may obtain a copy of the License at
%%%
%%%     http://www.apache.org/licenses/LICENSE-2.0
%%%
%%% Unless required by applicable law or agreed to in writing, software
%%% distributed under the License is distributed on an "AS IS" BASIS,
%%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%%% See the License for the specific language governing permissions and
%%% limitations under the License.

-define(SHEBANG, "{{eturnal_prefix}}/erts-{{release_erts_version}}/bin/escript").
-define(DEFAULT_LIB_DIR, "_build/default/lib").
-define(COMPILE_OPTS, [binary, deterministic | include_opts()]).

-spec main([string()]) -> ok.
main(Files) ->
    ok = maybe_compile_deps(),
    ok = lists:foreach(fun(File) -> ok = create_escript(File) end, Files).

-spec maybe_compile_deps() -> ok.
maybe_compile_deps() ->
    case os:getenv("REBAR_DEPS_DIR") of
        Dir when is_list(Dir) ->
            ok;
        false ->
            ok = io:put_chars(os:cmd("rebar3 compile"))
    end.

-spec create_escript(file:filename()) -> ok.
create_escript(File) ->
    {ok, _Mod, Code} = compile:file(File ++ ".erl", ?COMPILE_OPTS),
    ok = escript:create(File, [{shebang, ?SHEBANG}, {beam, Code}]),
    ok = file:change_mode(File, 8#00755).

-spec include_opts() -> [{i, string()}].
include_opts() ->
    LibDir = lib_dir(),
    CheckoutsDir = filename:join([filename:dirname(LibDir), "checkouts"]),
    case filelib:is_dir(CheckoutsDir) of
        true ->
            [{i, LibDir}, {i, CheckoutsDir}];
        false ->
            [{i, LibDir}]
    end.

-spec lib_dir() -> string().
lib_dir() ->
    case os:getenv("REBAR_DEPS_DIR") of
        Dir when is_list(Dir) ->
            Dir;
        false ->
            ?DEFAULT_LIB_DIR
    end.
