#!/usr/bin/perl
#
# File: ldap-schema-pp
# Description: LDAP schema pretty print
# Author: Bill MacAllister <bill@ca-zephyr.org>
# Copyright: 2022 Dropbox Inc.
# Copyright: 2022 Bill MacAllister <bill@ca-zephyr.org>
# Copyright: 2023 CZ Software

use Getopt::Long;
use Pod::Usage;
use strict;

our $opt_debug;
our $opt_help;
our $opt_manual;
our $opt_nonumbers;

##############################################################################
# Main routine
##############################################################################

# -- get options
GetOptions(
    'debug'     => \$opt_debug,
    'help'      => \$opt_help,
    'manual'    => \$opt_manual,
    'nonumbers' => \$opt_nonumbers
);

# -- help the poor souls out
if ($opt_help) {
    pod2usage(-verbose => 0);
}
if ($opt_manual) {
    pod2usage(-verbose => 2);
}

# Flush output immediately
$| = 1;

my @fold_list = (
    'to',  'by',       'filter',   'attrs',  'NAME',   'DESC',
    'SUP', 'ORDERING', 'EQUALITY', 'SUBSTR', 'SYNTAX', 'MAY',
    'MUST'
);

while (<>) {
    chomp;
    my $inline = $_;
    if ($opt_nonumbers) {
        $inline =~ s/(=|\s)[{]\d+[}]/$1/xmsg;
    }
    for my $t (@fold_list) {
        $inline =~ s/\s+($t(\s|=))/\n  $1/xmsg;
    }
    $inline =~ s/\s+(\$\s)/\n  $1/xmsg;
    print "$inline\n";
}

__END__

=head1 NAME

ldap-schema-pp - Pretty print LDIF schema

=head1 SYNOPSIS

ldap-schema-pp [--help] [--manual] [--debug] [--nonumbers]

=head1 DESCRIPTION

This script reformats output from cn=config LDAP searches.

=head1 AUTHOR

Bill MacAllister <bill@ca-zephyr.org>

=head1 COPYRIGHT

Copyright (C) 2022 Dropbox Inc.

License: Apache License, Version 2.0.

You may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Copyright 2022 Bill MacAllister <bill@ca-zephyr.org>

Copyright 2023 CZ Software

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

=cut
