#!/usr/bin/perl -w

use strict;
use DBI;

my $dbh;
my $sth_insert_files;

my $pkgkey=$ENV{'REPOCOP_PKG_KEY'};

&connect();

foreach my $filename(glob $ENV{'REPOCOP_PKG_ROOT'}."/etc/alternatives/packages.d/*") {
    open my $fh, $filename or die $!;
    my @content = <$fh>;
    close $fh;
    my $lineno=0;
    my $is_badsep=0;
    my $is_xml=0;
    if ($content[0]=~/<group/) {
	$is_xml=1;
	my ($link,$real,$criteria);
	foreach (@content){
	    chomp;
	    $link=$1 if m!<option\s*name="link">(.*)</option>!;
	    $real=$1 if m!<option\s*name="real">(.*)</option>!;
	    $criteria=$1 if m!<option\s*name="current">(.*)</option>!;
	    $criteria=$1 if m!<option\s*name="weight">(.*)</option>!;
	    if (m!</group>!) {
		$sth_insert_files->execute($pkgkey,$filename,$lineno,$link,$real,$criteria,$is_xml,$is_badsep);
		$lineno++;
	    }
	}
    } else {
	for($lineno=0;$lineno<@content;$lineno++){
	    chomp $content[$lineno];
	    next unless $content[$lineno];
	    my @tripple0=split("\t",$content[$lineno]);
	    my @tripple=split(/\s+/,$content[$lineno]);
	    $is_badsep=1 if $tripple0[0] ne $tripple[0] or $tripple0[1] ne $tripple[1] or $tripple0[2] ne $tripple[2];
	    $sth_insert_files->execute($pkgkey,$filename,$lineno,@tripple,$is_xml,$is_badsep);
	}
    }
}

&disconnect();

sub connect {
    my $dbfile=$ENV{'REPOCOP_TEST_DB'};
    die "database is not initialized properly!" unless $dbfile;
    $dbh = DBI->connect("dbi:SQLite:dbname=$dbfile","","", {
	PrintError => 1,
	AutoCommit => 0,
			}) or die $dbh->errstr;
    $sth_insert_files=$dbh->prepare('INSERT INTO altlinux_alternatives VALUES(?,?,?,?,?,?,?,?)') or die $dbh->errstr;
}

sub disconnect {
    $dbh->commit;
    $sth_insert_files->finish;
    # hack around closing dbh with active statement handles bug
    local $SIG{'__WARN__'} = sub {};
    $dbh->disconnect;
}

