#! /usr/bin/perl
use warnings;
use strict;
use integer;
use FindBin;
use lib $FindBin::RealBin;
use Def;
use Cmdsel;

# This helper script reports repeated entries in cmdsel.txt, whether the
# repetition is in the command's name and section or in its description.
# If the user names no cmdsel.txt file, the script examines the
# main debram.txt file in the expected place relative to the script.
#
# The script warns you if it notices a command out of its proper
# ram/man section.  It warns you and dies if a line is too long or is
# badly formatted.
#
# In addition to reporting repeats, the script also returns counts of
# command lines and commands (the difference being that a few command
# lines contain two or more commands, separated by commas) and branches.

our $n_dig_stat = 5;
our $usage = <<END;
usage: $0 [-h] { cmdsel.txt }
    -h print this usage message
END

# Read command-line arguments and options.
my @opt;
my @arg;
push @{ /^-\S/ ? \@opt : \@arg }, $_ for @ARGV;
my %opt = map {
  my $o = $_;
  map { substr( $o, $_, 1 ) => 1 } 1 .. length($o)-1
} @opt;
if ( $opt{'?'} || $opt{h} || @arg > 1 ) {
  print $usage;
  exit 0;
}
my $cmdsel = @arg ? shift(@arg) : $Def::cmdsel_txt;
die $usage if @arg;

# Read in and process.
open  F, '<', $cmdsel;
my $parse = Cmdsel::parse <F>;
close F;

my %line;
my %cmd ;
my %desc;

for my $ram ( keys %$parse ) {
  my $ram1 = $parse->{$ram};
  my $x    = $ram1->{x};
  for my $cmd ( keys %$x ) {
    my $cmd1 = $x->{$cmd};
    ++$cmd { $cmd1->{sect} }{$cmd};
    ++$desc{ $cmd1->{desc} } unless $line{ $cmd1->{line} };
    ++$line{ $cmd1->{line} };
  }
}

{
  print  "\nRepeated Commands:\n";
  print  "$_\n" for map {
    my $s  = $_      ;
    my $cs = $cmd{$s};
    map { "$_ ($s)" } grep { $cs->{$_} > 1 } sort keys %$cs;
  } sort keys %cmd;
  print  "\nRepeated Descriptions:\n";
  print  "$_\n" for grep { $desc{$_} > 1 } sort keys %desc;
  printf "\nCommand line count: %${n_dig_stat}d", scalar keys %line  ;
  {
    my $n;
    $n += scalar( keys %{ $cmd{$_} } ) for keys %cmd;
    printf "\nCommand count     : %${n_dig_stat}d", $n;
  }
  printf "\nBranch count      : %${n_dig_stat}d", scalar keys %$parse;
  print  "\n\n";
}

