# SPDX-License-Identifier: BSD-3-Clause-CMU
# See COPYING file at the root of the distribution for more details.
package Cyrus::IMAPOptions::App::Command::bitfields;
use warnings;
use strict;

use Cyrus::IMAPOptions::App -command;

sub abstract { 'build bitfields perl module from imapoptions' }

sub usage_desc { 'bitfields %o imapoptions' }

sub opt_spec { return Cyrus::IMAPOptions::App::common_opt_spec; }

sub validate_args
{
    my ($self, $opt, $args) = @_;

    $self->usage_error("need imapoptions path") if @$args < 1;
    $self->usage_error("too many arguments") if @$args > 1;

    $self->usage_error("imapoptions must be a directory")
        if ! -d $args->[0];
}

sub execute
{
    my ($self, $opt, $args) = @_;

    my $imapoptions = Cyrus::IMAPOptions->new(
        from_path => $args->[0],
        forbid_unreleased => $opt->forbid_unreleased,
    );

    $imapoptions->check_unreleased($self->app->arg0);

    $self->header();
    $imapoptions->iterate(\&_print_option, $opt);
    $self->footer();
}

sub header
{
    my ($self) = @_;

    my $pm = <<~'END_HEADER';
    # auto-generated by tools/imapoptions.pl
    package Cassandane::Config::Bitfields;
    use warnings;
    use strict;

    use Exporter qw(import);
    our @EXPORT_OK = qw();

    # XXX this doesn't differentiate real bit values from aliases
    our %bitfields = (
    END_HEADER

    print $pm;
}

sub footer
{
    my ($self) = @_;

    my $pm = <<~'END_FOOTER';
    );

    1;
    END_FOOTER

    print $pm;
}

sub _print_option
{
    my ($name, $option, $opt) = @_;

    return if $option->for_documentation_only;
    return if $option->type ne 'BITFIELD';

    print "    '" . $option->name . "' => {\n";

    foreach my $v ($option->allowed_values->values_and_aliases_flat) {
        print "        '$v' => 1,\n";
    }

    print "    },\n";
}

1;
