#!/usr/bin/perl 
#
# (c) by Uwe Drechsel
# 0.07	2011-10-14  Newer perl lib
# 0.06	2011-03-17  Added config file
# 0.05	2010-11-08  Showing severity only for PNEW bugs iwtn option -i
# 0.04	2010-11-04  Getting severity, too	
# 0.03	2010-08-05  quotation marks around bug data
# 0.02	2010-01-21  Adaption to be used in vym
# 0.01	2004-05-28  Initial version

my $VERSION=0.07;

# BugzillaClient can be installed from
# openSUSE:Tools

use lib '/usr/lib/perl5/vendor_perl/5.14.1/SUSE';

use BugzillaClient;
use POSIX qw(strftime);			# For time string in title

# Getting credentials from config file
my $CONFIG="$ENV{'HOME'}/.buggerrc";
my $USER;
my $PASS;

use Term::ReadKey;
use Fcntl;

if (! -e $CONFIG)
{
    print "bugger needs your login credentials for Bugzilla\n";
    print "and will store them in $CONFIG.\n\n";

    print "Login: ";
    $USER=<STDIN>; chomp ($USER);
    print "Password: ";
    ReadMode 'noecho';
    $PASS=<STDIN>; chomp ($PASS);
    ReadMode 'normal';
    my @file=("user=$USER\n","pass=$PASS\n");
    sysopen (FH, $CONFIG, O_RDWR|O_EXCL|O_CREAT, 0600);
    print (FH @file);
} else
{
    my $data=join ("",readfile ($CONFIG));
    $data=~/user=(.*)/;
    if ($1)
    {
	$USER=$1;
	$data=~/pass=(.*)/;
	if ($1)
	{
	    $PASS=$1;
	} else
	{
	    die "Couldn't find pass in $CONFIG";
	}
    } else
    {
	die "Couldn't find user in $CONFIG";
    }
}

# Login Data for accessing Novell iChain
# print "User=$USER  PASS=$PASS\n";
my $jar = SUSE::BugzillaClient::bzIChainConnect( $USER,$PASS );

use DBI;
use Getopt::Long;


# Default is HTML output
my %option = ( 'debug', 0);

#
# Basic definitions
#
# Base URLs
my $query_base_url="https://bugzilla.novell.com/";
my $showbug_base_url="https://bugzilla.novell.com/";

#
# End of basic definitions
#

GetOptions (
	"debug!"=>\$option{'debug'},
	"query=s"=>\$option{'query'},
	"f=s"=>\$option{'file'},
	"h!"=>\$option{'help'},
	"i!"=>\$option{'info'},
	"v!"=>\$option{'version'}
	);

if ($option{'help'})
{
    print <<HelpEnd;
Version $VERSION

  d               debug
  query=\$STRING  Query for URL \$STRING
  f=\$FILNAME     Add bugdata to \$FILENAME
  h               help
  i               info (used for release notes HP-BNB)
  v               show version


HelpEnd
}

if ($option{'version'})
{
    print "$VERSION\n";
    exit;
}

if ($option{'file'})
{
    my @lines=readfile ($option{'file'});
    my $i=0;
    while ($i<$#lines) 
    {
	if ($lines[$i]=~/bnc\s*#(\d+)/)
	{
	    print "Asking Bugzilla about \"$1\"...\n";
	    splice @lines,$i+1,0,"#### inserted ###################\n".
	    getBugInfo ($1*1);
	    $i++;
	}
	$i++;
    }
    system ("old $option{'file'}");

    writefile ($option{'file'},@lines);
    exit;
}

if ($option{'query'})
{
    print "Getting bugs (" . $option{'query'}.")\n" if ($option{'debug'});
    my $start = time() if ($option{'debug'});
    my @bugs = SUSE::BugzillaClient::getBugs($jar, $option{'query'});
    my $end = time() if ($option{'debug'});
    print STDERR " done (".scalar(@bugs).")\n" if( $DEBUG );
    print "query: " . ($end - $start) . " sec\n" if ($option{'debug'});

    foreach (@bugs) { printBug ($_); }

    exit;
}

if ($option{'info'})
{
    foreach (@ARGV)
    {
	print "" . getBugInfo ($_) ;
    }
    exit;
}

foreach (@ARGV)
{
    my $bug=SUSE::BugzillaClient::getBug ($jar, $_);
    printBug ($bug);
}    
exit;

############################################################
sub getBugInfo {
############################################################
    my $id=shift;
    my $bug=SUSE::BugzillaClient::getBug ($jar, $id);
    $bug->{priority}=~/^.*(P\d).*$/;
    my $s=$1;

    my $sev;
    if ($bug->{bug_severity}=="Critical")	{ $sev="S1";}
    elsif ($bug->{bug_severity}=="Major")	{ $sev="S2";}
    elsif ($bug->{bug_severity}=="Normal")	{ $sev="S3";}
    elsif ($bug->{bug_severity}=="Minor")	{ $sev="S4";}
    elsif ($bug->{bug_severity}=="Enhancement")	{ $sev="S5";}
    else {$sev="?";}


    if ($bug->{status_whiteboard}=~/PNEW/)
    {
	$s=$s."/".$sev;
    }

    if ($bug->{bug_status}=~/CLOSED|VERIFIED|RESOLVED/ ) { $s="($s)"; }

    $s=$s. " - $id - " . $bug->{'short_desc'};
    return  "    - $s\n" .
	    "      https://bugzilla.novell.com/show_bug.cgi?id=$id " .
	    " obs#$bug->{cf_partnerid}\n";
    #    if ( $bug->{cf_partnerid}=~/HP.*(\d+)/)
    #    {
    #	print " obs#$1";
    #    } else
    #    {
    #	print " obs#-";
    #    }
    #    print "\n";
}


############################################################
sub printBug {
############################################################
    my $bug=shift;
    binmode STDOUT, ":utf8";
    foreach (
	("short_desc",
	 "bug_status",
	 "status_whiteboard",
	 "priority",
	 "bug_severity",
	 "creation_ts",
	 "delta_ts",
	 "assigned_to",
	 "infoprovider",
	 "cf_partnerid",
	 "component") )
    {
	my $s=$bug->{$_};
	$s=~s/"/\\"/g;
	print $bug->{bug_id} . ":" . $_ .":\"" . $s . "\"\n";
    }

    #print  $bug->{bug_id} . ":short_desc:" .  $bug->{short_desc} . "\n";
    #print  $bug->{bug_id} . ":bug_status:" .  $bug->{bug_status} . "\n";
    #print  $bug->{bug_id} . ":status_whiteboard:" .  $bug->{status_whiteboard} . "\n";
    #print  $bug->{bug_id} . ":priority:" .  $_->{priority} . "\n";
    #print  $bug->{bug_id} . ":creation_ts:" .  $bug->{creation_ts} . "\n";
    #print  $bug->{bug_id} . ":delta_ts:" .  $bug->{delta_ts} . "\n";
}

############################################################
sub selectDataField {
############################################################
    my ($select)=@_;
    eval {
        $dbh=DBI->connect ($ds,$user,$pass,\%attrib);
    };
    die "$DBI::errstr\n" if ($@);


    eval {
        $sth=$dbh->prepare ("SELECT $select");
    };
    die "$DBI::errstr\n" if ($@);

    eval {
        $sth->execute();
    };
    die "$DBI::errstr\n" if ($@);
    return $sth->fetchrow_array();
}


############################################################
sub selectData {
############################################################
    my ($select)=@_;
    my @list;
    eval {
	    $dbh=DBI->connect ($ds,$user,$pass,\%attrib);
    };
    die "$DBI::errstr\n" if ($@);


    eval {
	    $sth=$dbh->prepare ("SELECT $select");
    };
    die "$DBI::errstr\n" if ($@);

    eval {
	    $sth->execute();
    };
    die "$DBI::errstr\n" if ($@);
    $, = ":";
    while (@row=$sth->fetchrow_array() ) {
	    push (@list,join (", ",@row));
    }
    return @list;
}


########################################################
sub readfile {                     
########################################################
	my ($filename) =@_;
	my (@lines);
	open (INFILE, "<$filename") || die "Couldn't read $filename";
	@lines=<INFILE>;
	return @lines;
}

########################################################
sub writefile {                    
########################################################
	$filename =shift(@_);
	open (OUTFILE, ">$filename") || die "Couldn't write $filename";
	print (OUTFILE @_);
}

