#!/usr/bin/perl -w

use strict;
use warnings;
use Test::Repocop::PkgId;
use Test::Repocop::Workdir;
use Test::Repocop::TestDB;
use Test::Repocop::Metadata;
use Test::Repocop::CLI::Base;
use Test::Repocop::Report::Tools;
our @ISA=qw/Test::Repocop::CLI/;
#$Repocop::arg::reportlevel='skip';
my $mysqlver=5;
my $packet_size=131072; #131072= 100kb
my $repocop_patch_url='http://repocop.altlinux.org/pub/repocop/reports/diff/by-srpm';

my $distro='altlinux';
my $branch='sisyphus';
my $component='classic';
my $dbfile;

our @LONGOPT=(
    # not used
    'b|branch=s' => \$branch,
    # not used
    "component=s"  => \$component,
    # not used
    "distribution=s"  => \$distro,

    "out=s"  => \$dbfile,

    'patchurl=s' => \$repocop_patch_url,
    'mysql=f' => \$mysqlver,
    'packetsize=i' => \$packet_size,
);
if (defined($dbfile) and -e $dbfile) {
    #warn "$dbfile already exists - removing\n";
    unlink $dbfile;
}
__PACKAGE__->get_and_process_cli_options();
&Test::Repocop::Workdir::die_if_nothing_to_report();

sub aquote {my @retval;foreach (@_) {push @retval, quote($_)}; return @retval};
#sub quote {$_=$_[0];s/'/''/g;s/\n/\\n/g;return $_};
sub quote {
	$_=$_[0];
	if (length($_)> 1000) {
		$_=substr($_,0,1000)."... [the rest of the message is skipped]"
	}
	s/'/''/g;
	return $_
};
sub max {return $_[1] unless defined $_[0]; if ($_[0]>=$_[1]) {return $_[0]}; return $_[1];}

sub sql_dump_row {
    my $ptrinsert_current=shift;
    my $ptrinsert=shift;
    my $ptrsize=shift;
    return unless $_[0];
    for (my $i=0; $i<@_;$i++) {
	$ptrsize->[$i]=max($ptrsize->[$i],length($_[$i]));
    }
    my $row="('".join("','",aquote(@_))."')";
    if (length($ptrinsert->[$$ptrinsert_current])+length($row)<$packet_size) {
	unless ($ptrinsert->[$$ptrinsert_current]) {
	    $ptrinsert->[$$ptrinsert_current]=$row;
	} else {
	    $ptrinsert->[$$ptrinsert_current].=','.$row;
	}
    } else {
	$ptrinsert->[++$$ptrinsert_current]=$row;
    }
}


my $repocop_insert_current=0;
my @repocop_insert=('');
my @repocop_size;

my $metadata=Test::Repocop::Metadata->new();
my $testdb=Test::Repocop::TestDB->new();
my $cache=$testdb->get_pkg_test_status_result_iterator();

#my $fh = *STDOUT;
my $fh=&Test::Repocop::Report::Tools::open_compressed_output($dbfile);

while (my ($pkgid,$test,$status,$result)=$cache->iterate4()) {
    my $name=$metadata->name($pkgid);
    my $version=$metadata->version($pkgid);
    my $release=$metadata->release($pkgid);
    my $arch=$metadata->arch($pkgid);
    my $sourceid=$metadata->sourceid($pkgid);
    my $srcname=$metadata->name($sourceid);
    my $srcversion=$metadata->version($sourceid);
    my $srcrelease=$metadata->release($sourceid);
    unless (defined $srcname && defined $name && defined $version && defined $release && defined $arch) {
	warn "internal error: broken metadata for $pkgid";
	next;
    }
    &sql_dump_row(\$repocop_insert_current,\@repocop_insert,\@repocop_size,
		  $name,$version,$release,$arch,$srcname,$srcversion,$srcrelease,$test,$status,$result);
}

if ($mysqlver < 4.99) {
    # mysql 4.0 varchars are no more 255 bytes
    @repocop_size = map {$_>255? 255:$_} @repocop_size;
}

print $fh q{
--
-- Table structure for table `repocop`
--

DROP TABLE IF EXISTS `repocop`;
CREATE TABLE `repocop` (
  `name` varchar(}.$repocop_size[0].q{) binary NOT NULL default '',
  `version` varchar(}.$repocop_size[1].q{) NOT NULL default '',
  `rel` varchar(}.$repocop_size[2].q{) NOT NULL default '',
  `arch` varchar(}.$repocop_size[3].q{) NOT NULL default 'i586',
  `srcname` varchar(}.$repocop_size[4].q{) binary NOT NULL default '',
  `srcversion` varchar(}.$repocop_size[5].q{) NOT NULL default '',
  `srcrel` varchar(}.$repocop_size[6].q{) NOT NULL default '',
  `testname` varchar(}.$repocop_size[7].q{) NOT NULL default '',
  `status` enum('skip','ok','experimental','info','warn','fail') NOT NULL default 'skip',
  `message` mediumtext,
  KEY `name` (`name`(30)),
  KEY `testname` (`testname`(30)),
  KEY `srcname` (`srcname`(30))
) TYPE=MyISAM;

--
-- Dumping data for table `repocop`
--
};
&print_dump($fh,'repocop',\@repocop_insert);

my $repocop_patchdir="$repocop_workdir/reports/diff/by-srpm";


unless (-d $repocop_patchdir) {
    warn "repocop patches not found. run repocop-fix-* first.\n";
    exit;
}

my $patches_insert_current=0;
my @patches_insert=('');
my @patches_size=(50,20,20,200);

foreach (glob "$repocop_patchdir/*") {
    s!^$repocop_patchdir/!!;
    my $patchname=$_;
    my $sourceid=&Test::Repocop::PkgId::patchname2srcid($patchname);
    my $name=$metadata->name($sourceid);
    my $version=$metadata->version($sourceid);
    my $release=$metadata->release($sourceid);
    my $url=$repocop_patch_url.'/'.$patchname;
    &sql_dump_row(\$patches_insert_current,\@patches_insert,\@patches_size,
		  $name,$version,$release,$url);
}

if ($mysqlver < 4.99) {
    # mysql 4.0 varchars are no more 255 bytes
    @patches_size = map {$_>255? 255:$_} @patches_size;
}

print $fh q{

--
-- Table structure for table `repocop_patches`
--

DROP TABLE IF EXISTS `repocop_patches`;
-- SET @saved_cs_client     = @@character_set_client;
-- SET character_set_client = utf8;
CREATE TABLE `repocop_patches` (
  `name` varchar(}.$patches_size[0].q{) binary NOT NULL default '',
  `version` varchar(}.$patches_size[1].q{) NOT NULL default '',
  `rel` varchar(}.$patches_size[2].q{) NOT NULL default '',
  `url` varchar(}.$patches_size[3].q{) NOT NULL default '',
  KEY `name` (`name`(20))
) TYPE=MyISAM;
-- SET character_set_client = @saved_cs_client;

--
-- Dumping data for table `repocop_patches`
--

};
&print_dump($fh,'repocop_patches',\@patches_insert);

&Test::Repocop::Report::Tools::close_compressed_output($fh);

#-------------------------------------

sub print_dump {
    my ($fh, $tablename,$dataptr)=@_;
    print $fh 'LOCK TABLES `'.$tablename.'` WRITE;
';
    print $fh 'ALTER TABLE `'.$tablename.'` DISABLE KEYS;
' if $mysqlver>4.0;
    foreach (@$dataptr) {
	print $fh 'INSERT INTO `'.$tablename.'` VALUES ',$_,";\n" if $_;
    }
    print $fh 'ALTER TABLE `'.$tablename.'` ENABLE KEYS;
' if $mysqlver>4.0;
    print $fh 'UNLOCK TABLES;
';
}

__END__

=head1	NAME

repocop-report-prometeus - a tool that reports repocop unit tests results to prometeus.

=head1	SYNOPSIS

B<repocop-report-prometeus>

=head1	DESCRIPTION

B<repocop-report-prometeus> processes results of repocop unit tests,
created with repocop-run command, stored in <workdir>,
and publishes results to prometeus.
Presize subset of tests can be selected using B<--include>
and B<--exclude> options.

=head1	OPTIONS

=over

see repocop-report-txt

=back

=head1	AUTHOR

Written by Igor Vlasenko <viy@altlinux.org>.

=head1	ACKNOWLEGEMENTS

To Alexey Torbin <at@altlinux.org>, whose qa-robot package
had a strong influence on repocop.

=head1	COPYING

Copyright (c) 2008-2021 Igor Vlasenko, ALT Linux Team.

This is free software; you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation;
either version 2 of the License, or (at your option) any later version.

=cut

