src/rebar_calzone_pack.erl

% SPDX-FileCopyrightText: 2026 Dipl. Phys. Peer Stritzinger GmbH
%
% SPDX-License-Identifier: Apache-2.0

-module(rebar_calzone_pack).

% Exports
-export([bake/1]).

%--- Macros --------------------------------------------------------------------

-define(BAKER, "baker").
-define(LAUNCHER, "launcher").

%--- API -----------------------------------------------------------------------

bake(#{mode := escript} = Options) ->
    #{name := ScriptName,
      calzone_dir := CalzoneDir,
      version := Version} = Options,
    {BakerPath, LauncherPath} = calzone_bins(),
    BaseArgs = [
        "--launcher", LauncherPath,
        "--payload", CalzoneDir,
        "--output", output_bin_name(Options),
        "--meta APP_NAME=" ++ ScriptName,
        "--meta APP_VER=" ++ Version,
        "--meta ENTRY_POINT=bin/escript"
    ],
    EnvArgs = [
        "--meta", "ENV.ROOTDIR={PAYLOAD_ROOT}",
        "--meta", "ENV.ERL_FLAGS=\"+replay {PAYLOAD_ROOT}/mmap_recordings\""
    ],
    EntryArgs = [
        "--meta", "ENTRY_ARGS[]={PAYLOAD_ROOT}/bin/" ++ ScriptName
    ],
    Args = BaseArgs ++ EnvArgs ++ EntryArgs,
    Command = lists:join(" ", [BakerPath | Args]),
    rebar_api:debug("sh: ~s", [string:join(Command, " ")]),
    rebar_calzone_utils:sh(Command);
bake(#{mode := release} = _Options) ->
    rebar_api:abort("Release mode not supported", []).

%--- Private -------------------------------------------------------------------
calzone_bins() ->
    case {os:find_executable(?BAKER), os:find_executable(?LAUNCHER)} of
        {false, _} ->
            rebar_api:abort("Unable to locate baker's binary", []);
        {_, false} ->
            rebar_api:abort("Unable to locate launcher's binary", []);
        Bins ->
            Bins
    end.

output_bin_name(Options) ->
    #{target_os := OS,
      target_arch := Arch,
      name := Name} = Options,
    Name ++ "-" ++ atom_to_list(OS) ++ "-" ++ arch_to_string(Arch) ++ ".bin".

arch_to_string(x86_64) -> "amd64";
arch_to_string(aarch64) -> "arm64".