#!/usr/bin/perl -w

use strict;

use lib "/usr/share/request-tracker3.6/lib";
use RT;
RT::LoadConfig;
$RT::LogToScreen = 'notice';
RT::InitLogging;

$RT::Logger->debug("request-tracker3.6.postinst: running $0 to fix the database (bug #442398)");

$RT::Logger->debug("Connecting to the database");
require RT::Handle;
$RT::Handle = RT::Handle->new();
$RT::Handle->Connect();

my $CurrentUser = new RT::CurrentUser();

my $attr = RT::Attribute->new($CurrentUser);

$RT::Logger->debug("Loading the possibly broken attribute");
$attr->LoadByCols(Name => "Search - My Tickets");

my $format = $attr->SubValue('Format');
# $RT::Logger->debug("Format value: $format");

my @matches = ($format =~ m{href="([^"]*)/Ticket/Display.html}g);

my $found = 0;

for my $match (@matches) {
    next if $match eq "__WebPath__";
    $found++;
    $RT::Logger->notice("Replacing webpath \"$match\" with __WebPath__");
    $format =~ s{href="\Q$match\E/Ticket/Display.html}{href="__WebPath__/Ticket/Display.html};
    $attr->SetSubValues(Format => $format);
    $RT::Logger->debug("Format now: $format");
}
if ($found) {
    $RT::Logger->notice("Database fixed succesfully");
} else {
    $RT::Logger->debug("Finished, nothing to do.");
}

