#!/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 $!;
    $filename=~s/^$ENV{'REPOCOP_PKG_ROOT'}//;
    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,$master_criteria,$slave_criteria);
	foreach (@content){
	    chomp;
	    $link=$1 if m!<option\s*name="link">(.*)</option>!;
	    $real=$1 if m!<option\s*name="real">(.*)</option>!;
	    $master_criteria=$1 if m!<option\s*name="current">(.*)</option>!;
	    $master_criteria=$1 if m!<option\s*name="weight"(?:\s+type="number")?>(.*)</option>!;
	    if ($master_criteria) {
		$sth_insert_files->execute($pkgkey,$filename,$lineno,$link,$real,$master_criteria,1,$is_xml,$is_badsep);
		$lineno++;
		$slave_criteria=$real;
		$master_criteria=undef;
		$link=undef;
		$real=undef;
	    }
	    if (m!</group>! and $link and $real) {
		$sth_insert_files->execute($pkgkey,$filename,$lineno,$link,$real,$slave_criteria,0,$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]);
	    my $is_master=0;
	    $is_master=1 if $tripple[2]=~/^\d+$/;
	    $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_master,$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;
}

