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

use experimental 'signatures';

use Cyrus::IMAPOptions::App -command;

use Cyrus::IMAPOptions;

sub abstract () { 'build a sample imapd.conf file from imapoptions' }

sub usage_desc (@) { 'sample %o imapoptions' }

sub opt_spec (@) { return Cyrus::IMAPOptions::App::common_opt_spec; }

sub validate_args ($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 ($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);
}

sub header ($self)
{
    my $sample = <<~'END_HEADER';
    ## auto-generated by tools/imapoptions.pl
    END_HEADER

    print $sample;
}

sub _print_option ($name, $option)
{
    my $underline = '-' x length $name;

    print "# $name\n# $underline\n";

    if ($option->has_documentation) {
        foreach my $line ($option->documentation->@*) {
            chomp $line;

            print $line
                  ? "# $line\n"
                  : "#\n";
        }
    }

    if ($option->has_deprecated_since) {
        if ($option->has_replaced_by) {
            print '# Deprecated in favour of ';
            print $option->replaced_by;
            print ".\n";
        }
        else {
            print "# Deprecated. No longer used.\n";
        }
        print "\n";
    }
    elsif ($option->has_allowed_values) {
        print "\n";
        print '# Allowed values: ';
        print join(', ', $option->allowed_values->values);
        print "\n";
    }

    print "#$name: ". $option->docs_default_value . "\n\n";
}

1;
