#! /usr/bin/perl

=head1 DESCRIPTION

    По файлу .schema.sql составляет шаблон описания таблицы с разметкой Markdown Extra

=head1 SYNOPSIS

    direct-table-description <файл схемы таблицы> [ <файл схемы таблицы> ]
    direct-table-description db_schema/ppc/campaigns.schema.sql

    В качестве аргументов командной строки скрипт ожидает один или несколько файлов со схемами таблиц. 
    Для каждой таблицы рядом с файлом схемы создается файл .text с шаблоном описания таблицы. 

    Если файл уже существовал -- будет выдано сообщение, и файл не поменяется. 

    Созданные файлы добавляются к рабочей копии (svn add)

=head1 COMMMENTS

=cut

use strict;
use warnings;

use File::Slurp;
use Getopt::Long;

use utf8;
use open ':locale';

GetOptions (
    "h|help"       => \&usage,
) or die "incorrect options";

for my $schema_file ( @ARGV  ){ 
    if ( $schema_file !~ /\.schema\.sql$/ ){
        print "$schema_file -- incorrect filename\n";
	next;
    }

    (my $desc_file = $schema_file) =~ s/\.schema\.sql/.text/;

    if ( -e $desc_file ){
        print "$desc_file already exists\n";
	next;
    }

    my ($table) = $schema_file =~ /([^\/\.]+)\.schema\.sql/;
    $table ||= '<Имя таблицы>';
    my $title_line = '-' x length $table;

    my @lines = read_file($schema_file);
    @lines = grep { /^  `/ } @lines;
    map { s/^ *`// } @lines;
    map { s/`.*/\n:   <описание>\n/ } @lines;

    my $text = "$table\n$title_line\n\n<общее описание таблицы>\n\n### Столбцы: ###\n\n". join('', @lines);

    write_file($desc_file, {atomic => 1, binmode => ':utf8'}, $text);
    `svn add $desc_file`;
    print "ready: $desc_file\n";

#    print qq!cat $schema_file |grep '^  `' |sed 's/^ *`//' |sed 's/`.*/\\n:<описание>\\n/' | ( echo "$table\n$title_line\n\n<общее описание таблицы>\n\n### Столбцы: ###\n" ; while read i ; do echo \$i ; done ) > $desc_file !;
#    qx!cat $schema_file |grep '^  `' |sed 's/^ *`//' |sed 's/`.*/\\n:   <описание>\\n/' | ( echo "$table\n$title_line\n\n<общее описание таблицы>\n\n### Столбцы: ###\n" ; while read i ; do echo \$i ; done ) > $desc_file !;

}

exit;

sub usage {
    system("podselect -section SYNOPSIS -section DESCRIPTION $0 | pod2text-utf8 >&2");
    exit(1);
}

