#!/usr/bin/perl -w
use strict;

my $dn = `dirname $0`;chomp($dn);
my $pwd = `pwd`;chomp($pwd);
if ($dn !~ /^\//) { $dn = $pwd . "/" . $dn; }
push @INC,$dn;
my $cverepobase=`dirname $dn`;
chomp($cverepobase);

require SMASHData;
require CanDBReader;

my ($dummy1,$dummy2,$dummy3,$mday,$mon,$year,$dummy4,$dummy5,$dummy6) = localtime(time);
$year+=1900;
my $date = sprintf("%04d%02d%02d",$year,$mon+1,$mday);

my %handled = ();

my %map = %{&SMASHData::fetch_last_smash_issues()};

my %cves = %{$map{'bug'}};
my %embargoed = %{$map{'embargo'}};

my $lines = "";

foreach my $cve (keys %cves) {
	foreach my $bug (sort keys %{$cves{$cve}}) {
		if (!defined($CanDBReader::bugzillas{$cve}) || !grep (/$bug/, $CanDBReader::bugzillas{$cve})) {
			$lines .= "$cve,$date,BUGZILLA:$bug\n";
		}
	}
	if ($embargoed{$cve} && !$CanDBReader::embargoed{$cve}) {
		$lines .= "$cve,$date,EMBARGOED:1\n";
	}
	$handled{$cve} = 1;
}

my @allvulns = `find $cverepobase/vulns/ -name "CVE-*.json"`;
foreach my $vuln (@allvulns) {
	chomp $vuln;
	$vuln =~ s/.*CVE/CVE/; 
	$vuln =~ s/.json//; 

	&SMASHData::read_smash_issue($vuln);
}


%map = %{&SMASHData::fetch_modified_smash_issues()};
%cves = %{$map{'bug'}};
%embargoed = %{$map{'embargo'}};
foreach my $cve (keys %cves) {
	next if ($handled{$cve});
	foreach my $bug (sort keys %{$cves{$cve}}) {
		if (!defined($CanDBReader::bugzillas{$cve}) || (!grep (/$bug/, $CanDBReader::bugzillas{$cve}))) {
			$lines .= "$cve,$date,BUGZILLA:$bug\n";
		}
	}
	if ($embargoed{$cve} && !$CanDBReader::embargoed{$cve}) {
		$lines .= "$cve,$date,EMBARGOED:1\n";
	}
}

if ($lines ne "") {
	if (open(CANNUMBERS,">>/suse/meissner/Export/can-numbers")) {
		print CANNUMBERS $lines;
		close(CANNUMBERS);
	} else {	# in securitybot
		if (open(CVE2BUGZILLA,">>$cverepobase/data/cve2bugzilla")) {
			print CVE2BUGZILLA $lines;
			close(CVE2BUGZILLA);
		}
	}
}

&SMASHData::read_all_cached_issues();

# random refresh
foreach my $cve (keys %SMASHData::pkgstate) {
        next unless ($cve =~ /^(CAN|CVE)-(\d*)-\d*$/);

	next unless (%{$SMASHData::pkgstate{$cve}});

        my $cveyear = $2;

        if (int(rand(($year-$cveyear+1)*4)) == 0) {     # refresh every 4th cve in current year, every 8th in second last, 12th in third last ... on every run
                &SMASHData::read_smash_issue($cve,1);
        }

}

# random refresh 2
foreach my $cve (keys %CanDBReader::bugzillas) {
        next unless ($cve =~ /^(CAN|CVE)-(\d*)-\d*$/);

        my $cveyear = $2;

        if (int(rand(($year-$cveyear+1)*6)) == 0) {     # refresh every 6th cve in current year, every 12th in second last, 18th in third last ... on every run
                &SMASHData::read_smash_issue($cve,1);
        }

}



if ($lines ne "") {
	print STDERR "added to can-numbers: $lines\n";
}

1;
