# 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 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
{
    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);
}

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

    my $sample = <<~'END_HEADER';
    ## auto-generated by tools/imapoptions.pl
    END_HEADER

    print $sample;
}

sub _print_option
{
    my ($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;
