#!/usr/local/bin/perl -w

use strict;
use warnings;

use lib qw(. lib);

use Bugzilla;
use Bugzilla::Constants;
use Bugzilla::User;

use constant WAIT => 30;
use constant AUTOMATION_USER => 'bugzilla@freebsd.org';

# We're a non-interactive user
Bugzilla->usage_mode(USAGE_MODE_CMDLINE);

# Get the db conection and query the db directly.
my $dbh = Bugzilla->dbh;

my $dnow = $dbh->sql_to_days("NOW()");
my $maintainer_query = q{
SELECT DISTINCT
  bugs.bug_id, flags.id
FROM
  bugs
  JOIN bug_status bs ON (bs.value = bugs.bug_status AND bs.is_open != 0)
  JOIN flags ON (bugs.bug_id = flags.bug_id AND flags.status = '?')
  JOIN flagtypes ON (flags.type_id = flagtypes.id)
WHERE
  flagtypes.name = 'maintainer-feedback'
  AND } . $dnow . " - " . $dbh->sql_to_days("flags.modification_date") . " >= " . WAIT .
" AND flags.attach_id is NULL
  ORDER BY bugs.bug_id
";

my $openbugs = $dbh->selectall_arrayref($maintainer_query);

# If there are no bugs (hah!), exit gracefully
if (scalar(@$openbugs) == 0) {
    exit 0;
}

# Switch the user session
my $autoid = login_to_id(AUTOMATION_USER);
die("automation user " . AUTOMATION_USER . "does not exist") if(!$autoid);
Bugzilla->set_user(new Bugzilla::User($autoid));


my %flags;

foreach my $b (@$openbugs) {
    my ($bug_id, $flag_id) = @{$b};
    if (!defined($flags{$bug_id})) {
        $flags{$bug_id} = [ $flag_id ];
    }
    else {
        push @{$flags{$bug_id}}, $flag_id;
    }
}
foreach my $bug_id (keys %flags) {
    my (@oldflags, @newflags);
    my $bug = Bugzilla::Bug->new($bug_id);
    foreach my $flag_id (@{$flags{$bug_id}}) {
        my $flag = Bugzilla::Flag->new($flag_id);
        my $new_flag = {
            id              => $flag_id,
            type_id         => $flag->type_id,
            status          => "-",
            requestee_id    => $flag->requestee_id,
            bug_id          => $flag->bug_id,
        };
        push @newflags, $new_flag;
    }
    $bug->set_flags(\@oldflags, \@newflags);
    $bug->update();
}
