#!/usr/bin/env escript
main([]) ->
    Path = filename:join([
        filename:dirname(filename:absname(?FILE)),
        "..",
        "include",
        "merlin_oneof.hrl"
    ]),
    {ok, CurrentWorkingDirectory} = file:get_cwd(),
    RelativePath1 =
        case string:prefix(?FILE, CurrentWorkingDirectory ++ "/") of
            nomatch -> ?FILE;
            RelativePath0 -> RelativePath0
        end,
    {ok, File} = file:open(Path, [write]),
    write_lines(File, [
        "%% % @noformat",
        ["%% Automatically generated by ", RelativePath1],
        "%% Do not edit by hand",
        "",
        "-ifndef(MERLIN_ONEOF).",
        "-define(MERLIN_ONEOF, true).",
        "",
        "%% Allow mixing this and `in' macros without running the parse transform twice",
        "-ifndef(MERLIN_IN).",
        "-compile({parse_transform, merlin_in_transform}).",
        "-endif."
    ]),
    %% Can't use lists:map(fun define_oneof/1, ...) here.
    %% For some reason then it becomes erl_eval:define_oneof/1 instead of
    %% referring to the function below.
    [
        begin
            io:nl(File),
            write_lines(File, define_oneof(Arity))
        end
     || Arity <- lists:seq($A, $Z)
    ],
    write_lines(File, [
        "-endif."
    ]),
    file:close(File).

write_lines(File, Lines) ->
    io:put_chars(File, lists:join($\n, Lines)),
    io:nl(File).

define_oneof(LastArgument) ->
    Arguments = lists:join(", ", lists:seq($A, LastArgument)),
    [
        ["-define(oneof(", Arguments, "),"],
        ["     merlin_in_transform:'ONE OF'(", Arguments, ")"],
        ")."
    ].
