# Initial data for a fresh RTIR Installation.

die "Please add RT::IR to your Plugins configuration before initializing the database. See README for more information."
    unless grep { $_ eq 'RT::IR' } RT->Config->Get('Plugins');

@Initial = (
    sub {
        use RT::IR;
        RT::Lifecycle->FillCache;
        return 1;
    },
);

@Queues = map {
    {   Name              => RT::IR::FriendlyLifecycle($_),
        Lifecycle         => $_,
        CorrespondAddress => "",
        CommentAddress    => "",
        InitialPriority   => (
            $_ eq 'incidents'
            ? 50
            : 0
        ),
        SLADisabled => ( $_ eq 'incidents' ? 1 : 0 ),
    }
} RT::IR->Lifecycles;

@CustomFields = (
    {   Name        => 'RTIR Constituency',
        Type        => 'SelectSingle',
        Disabled    => 0,
        RenderType  => 'Dropdown',
        LookupType  => 'RT::Queue',
        Description => 'Associates RTIR queues with constituencies',
        Values      => []
    },
    {   Name       => 'RTIR default WHOIS server',
        Type       => 'FreeformSingle',
        Disabled   => 0,
        LookupType => 'RT::Queue',
        Description =>
            'If set, defines the default WHOIS server for an RTIR Queue',
        ApplyTo => [ map { $_->{Name} } @Queues ]
    },
    {   Name        => 'Classification',
        Type        => 'SelectSingle',
        RenderType  => 'Dropdown',
        Queue       => 'Incidents',
        Disabled    => 0,
        Description => 'Classification for Incidents RTIR queue',
        Values      => [
            { Name => "Spam",              SortOrder => 1 },
            { Name => "System Compromise", SortOrder => 2 },
            { Name => "Query",             SortOrder => 3 },
            { Name => "Scan",              SortOrder => 4 },
            { Name => "Denial of Service", SortOrder => 5 },
            { Name => "Piracy",            SortOrder => 6 },
        ],
    },
    {   Name        => 'Function',
        Type        => 'SelectSingle',
        RenderType  => 'Dropdown',
        Queue       => 'Incidents',
        Disabled    => 0,
        Description => 'Function for Incidents RTIR queue',
        Values      => [
            { Name => "AbuseDesk",     SortOrder => 1 },
            { Name => "IncidentCoord", SortOrder => 2 },
        ],
    },
    {   Name        => 'Resolution',
        Type        => 'SelectSingle',
        RenderType  => 'Dropdown',
        Queue       => 'Incidents',
        Disabled    => 0,
        Description => 'Resolution for Incidents RTIR queue',
        Values      => [
            { Name => 'successfully resolved',      SortOrder => 1 },
            { Name => 'no resolution reached',      SortOrder => 2 },
            { Name => 'no response from customer',  SortOrder => 3 },
            { Name => 'no response from other ISP', SortOrder => 4 },
        ],
    },
    {
        Name        => 'CVE ID',
        Type        => 'FreeformMultiple',
        Queue       => [ 'Incidents', 'Incident Reports', 'Investigations', 'Countermeasures' ],
        Disabled    => 0,
        Description => 'CVE ID for RTIR queues',
        LinkValueTo => 'https://nvd.nist.gov/vuln/detail/__CustomField__#vulnCurrentDescriptionTitle',
    },

    {   Name       => 'How Reported',
        Type       => 'SelectSingle',
        RenderType => 'Dropdown',
        Queue      => 'Incident Reports',
        Disabled   => 0,
        Description =>
            'How the incident was reported for Incident Reports RTIR queue',
        Values => [
            { Name => "API",       SortOrder => 1 },
            { Name => "CLI",       SortOrder => 2 },
            { Name => "Email",     SortOrder => 3 },
            { Name => "REST",      SortOrder => 4 },
            { Name => "REST2",     SortOrder => 5 },
            { Name => "Web",       SortOrder => 6 },
            { Name => "Telephone", SortOrder => 7 },
            { Name => "Other",     SortOrder => 8 },
        ]
    },
    {   Name        => 'Reporter Type',
        Type        => 'SelectSingle',
        RenderType  => 'Dropdown',
        Queue       => 'Incident Reports',
        Disabled    => 0,
        Description => 'Reporter type for Incident Reports RTIR queue',
        Values      => [
            { Name => "customer",            SortOrder => 1 },
            { Name => "external individual", SortOrder => 2 },
            { Name => "other ISP",           SortOrder => 3 },
            { Name => "police",              SortOrder => 4 },
            { Name => "other IRT",           SortOrder => 5 },
            { Name => "other",               SortOrder => 6 },
        ]
    },
    {   Name => 'IP',
        Type => 'IPAddressRangeMultiple',
        Queue =>
            [ 'Incidents', 'Incident Reports', 'Investigations', 'Countermeasures' ],
        Disabled    => 0,
        Description => 'IP address for RTIR queues',
        LinkValueTo =>
            '__WebPath__/RTIR/Tools/Lookup.html?type=ip&q=__CustomField__&ticket=__id__'
    },
    {   Name        => 'Netmask',
        Type        => 'FreeformSingle',
        Queue       => 'Countermeasures',
        Disabled    => 0,
        Description => 'Network mask for Countermeasures',
    },
    {   Name        => 'Port',
        Type        => 'FreeformSingle',
        Queue       => 'Countermeasures',
        Disabled    => 0,
        Description => 'Port for Countermeasures',
    },
    {   Name        => 'Where Blocked',
        Type        => 'FreeformSingle',
        Queue       => 'Countermeasures',
        Disabled    => 0,
        Description => 'Where the block is placed for Countermeasures',
    },
    {   Name        => 'Customer',
        Type        => 'SelectMultiple',
        Queue       => 'Incident Reports',
        Disabled    => 0,
        Values      => [],
        Description => 'Customer for Incident Reports RTIR queue',
    },
    {   Name        => 'Customer',
        Type        => 'SelectSingle',
        RenderType  => 'Dropdown',
        Queue       => 'Investigations',
        Disabled    => 0,
        Values      => [],
        Description => 'Customer for Investigations RTIR queue',
    },
    {
        Name        => 'Domain',
        Type        => 'FreeformMultiple',
        Queue       => [ 'Incidents', 'Incident Reports', 'Investigations', 'Countermeasures' ],
        Disabled    => 0,
        Description => 'Domain for RTIR queues',
        LinkValueTo =>
            '__WebPath__/RTIR/Tools/Lookup.html?type=host&q=__CustomField__&ticket=__id__'
    },
);

@ScripActions = (
    {   Name        => 'RTIR Set Incident Due',                  # loc
        Description => 'Set the due date of parent Incident',    # loc
        ExecModule  => 'RTIR_SetDueIncident',
    },
    {   Name        => 'RTIR Set How Reported',                       # loc
        Description => 'Set how the Incident Report was reported',    # loc
        ExecModule  => 'RTIR_SetHowReported',
    },
    {   Name        => 'RTIR Resolve Children',                       # loc
        Description => "Resolve an Incident's children",              # loc
        ExecModule  => 'RTIR_ResolveChildren',
    },
    {   Name        => 'RTIR Change Child Ownership',                    # loc
        Description => "Change the ownership of Incident's children",    # loc
        ExecModule  => 'RTIR_ChangeChildOwnership',
    },
    {   Name        => 'RTIR Change Parent Ownership',                   # loc
        Description => 'Change the ownership of the parent Incident',    # loc
        ExecModule  => 'RTIR_ChangeParentOwnership',
    },
    {   Name        => 'RTIR Open Parent',                               # loc
        Description => 'Open the parent Incident when a child reopens',  # loc
        ExecModule  => 'RTIR_OpenParent',
    },
    {   Name        => 'RTIR Set Countermeasure Status',                 # loc
        Description => 'Set the status of a Countermeasure',             # loc
        ExecModule  => 'RTIR_SetCountermeasureStatus',
    },
    {   Name        => 'RTIR Set Incident Resolution',                   # loc
        Description => 'Set the default resolution of an Incident',      # loc
        ExecModule  => 'RTIR_SetIncidentResolution',
    },
    {   Name        => 'RTIR parse message for IPs',                     # loc
        Description => 'Set IP custom field from message content',       # loc
        ExecModule  => 'RTIR_FindIP',
    },
    {   Name        => 'RTIR merge IPs',                                 # loc
        Description => 'Merge multiple IPs on ticket merge',             # loc
        ExecModule  => 'RTIR_MergeIPs',
    },
    {   Name        => 'RTIR Activate Ticket',                           # loc
        Description => 'Set status to first active possible',            # loc
        ExecModule  => 'RTIR_Activate',
    },
    {   Name => 'RTIR Change Child Constituencies',
        Description =>
            'Move all tickets related to an incident to a new constituency',
        ExecModule => 'RTIR_ChangeChildConstituencies'
    },
    {   Name        => 'RTIR parse message for Domains',                 # loc
        Description => 'Set Domain custom field from message content',   # loc
        ExecModule  => 'RTIR_FindDomain',
    },
    {   Name        => 'RTIR merge Domains',                                 # loc
        Description => 'Merge multiple Domains on ticket merge',             # loc
        ExecModule  => 'RTIR_MergeDomains',
    },
    {   Name        => 'RTIR parse message for CVEs',                 # loc
        Description => 'Set CVE custom field from message content',   # loc
        ExecModule  => 'RTIR_FindCVE',
    },
    {   Name        => 'RTIR merge CVEs',                                 # loc
        Description => 'Merge multiple CVEs on ticket merge',             # loc
        ExecModule  => 'RTIR_MergeCVEs',
    },
);

@ScripConditions = (

    {   Name                 => 'RTIR Customer Response',                # loc
        Description          => 'Detect an external response',           # loc
        ApplicableTransTypes => 'Correspond',
        ExecModule           => 'RTIR_CustomerResponse',
    },
    {   Name                 => 'RTIR Staff Response',                   # loc
        Description          => 'Detect an internal response',           # loc
        ApplicableTransTypes => 'Correspond',
        ExecModule           => 'RTIR_StaffResponse',
    },
    {   Name                 => 'RTIR Close Ticket',                     # loc
        Description          => 'A ticket is rejected or resolved',      # loc
        ApplicableTransTypes => 'Any',
        ExecModule           => 'StatusChange',
        Argument             => 'old: initial, active; new: inactve',
    },
    {   Name                 => 'RTIR Reopen Ticket',                    # loc
        Description          => 'A closed ticket is reopened',           # loc
        ApplicableTransTypes => 'Any',
        ExecModule           => 'StatusChange',
        Argument             => 'old: inactive; new: initial, active',
    },
    {   Name => 'RTIR Require Due Change',                               # loc
        Description =>
            'The due date of the parent incident must be changed',       # loc
        ApplicableTransTypes => 'Any',
        ExecModule           => 'RTIR_RequireDueChange',
    },
    {   Name => 'RTIR Linking To Incident',                              # loc
        Description =>
            'Whenever ticket is linked to incident or created with link'
        ,                                                                # loc
        ApplicableTransTypes => 'Create,AddLink',
        ExecModule           => 'RTIR_LinkingToIncident',
    },
    {   Name        => 'RTIR Merge',                                     # loc
        Description => 'Whenever ticket is merged into another one',     # loc
        ApplicableTransTypes => 'AddLink',
        ExecModule           => 'RTIR_Merge',
    },
    {   Name                 => 'RTIR Require IRs Activation',           # loc
        Description          => "Whenever it's time to activate report", # loc
        ApplicableTransTypes => 'Correspond',
        ExecModule           => 'RTIR_RequireReportActivation',
    },
);

@Scrips = (
    {   Description    => "SetHowReported",
        Queue          => 'Incident Reports',
        ScripCondition => 'On Create',
        ScripAction    => 'RTIR Set How Reported',
        Template       => 'Blank'
    },

    {   Description    => "On Correspond Change Status of the Countermeasure",
        Queue          => 'Countermeasures',
        ScripCondition => 'On Correspond',
        ScripAction    => 'RTIR Set Countermeasure Status',
        Template       => 'Blank',
    },
    {   Description    => "On Linking To Incident Activate Report",
        Queue          => 'Incident Reports',
        ScripCondition => 'RTIR Linking To Incident',
        ScripAction    => 'RTIR Activate Ticket',
        Template       => 'Blank'
    },
    {   Description    => "On Correspond (not every) Activate Report",
        Queue          => 'Incident Reports',
        ScripCondition => 'RTIR Require IRs Activation',
        ScripAction    => 'RTIR Activate Ticket',
        Template       => 'Blank'
    },
    {   Description    => "On Linking To Incident Copy IPs",
        Queue          => 'Incident Reports',
        ScripCondition => 'RTIR Linking To Incident',
        ScripAction    => 'RTIR merge IPs',
        Template       => 'Blank'
    },

    {   Description    => "Set Due Date On Incident",
        Queue          => [ 'Incident Reports', 'Investigations', 'Countermeasures' ],
        ScripCondition => 'RTIR Require Due Change',
        ScripAction    => 'RTIR Set Incident Due',
        Template       => 'Blank',
    },

    {   Description    => "ResolveAllChildren",
        Queue          => 'Incidents',
        ScripCondition => 'On Status Change',
        ScripAction    => 'RTIR Resolve Children',
        Template       => 'Blank',
    },

    {   Description    => "Propagate Constituency Changes",
        Queue          => 'Incidents',
        ScripCondition => 'On Queue Change',
        ScripAction    => 'RTIR Change Child Constituencies',
        Template       => 'Blank',
    },

    {   Description    => "FixOwnership",
        Queue          => 'Incidents',
        ScripCondition => 'On Owner Change',
        ScripAction    => 'RTIR Change Child Ownership',
        Template       => 'Blank',
    },
    {   Description    => "FixOwnership",
        Queue          => [ 'Incident Reports', 'Investigations', 'Countermeasures' ],
        ScripCondition => 'On Owner Change',
        ScripAction    => 'RTIR Change Parent Ownership',
        Template       => 'Blank',
    },

    {   Description    => "ReopenIncident",
        Queue          => [ 'Incident Reports', 'Investigations', 'Countermeasures' ],
        ScripCondition => 'On Status Change',
        ScripAction    => 'RTIR Open Parent',
        Template       => 'Blank',
    },

    {   Description    => "SetDefaultIncidentResolution",
        Queue          => 'Incidents',
        ScripCondition => 'On Status Change',
        ScripAction    => 'RTIR Set Incident Resolution',
        Template       => 'Blank',
    },

    {   Description    => "NotifyOnClose",
        Queue          => 'Countermeasures',
        ScripCondition => 'RTIR Close Ticket',
        ScripAction    => 'Notify Requestors',
        Template       => 'CountermeasureRemoved'
    },

    {   Description => "SetIPFromContent",
        Queue =>
            [ 'Incidents', 'Incident Reports', 'Investigations', 'Countermeasures' ],
        ScripCondition => 'On Correspond',
        ScripAction    => 'RTIR parse message for IPs',
        Template       => 'Blank'
    },
    {   Description => "SetIPFromContent",
        Queue =>
            [ 'Incidents', 'Incident Reports', 'Investigations', 'Countermeasures' ],
        ScripCondition => 'On Create',
        ScripAction    => 'RTIR parse message for IPs',
        Template       => 'Blank'
    },

    {   Description => "MergeIPs",
        Queue =>
            [ 'Incidents', 'Incident Reports', 'Investigations', 'Countermeasures' ],
        ScripCondition => 'RTIR Merge',
        ScripAction    => 'RTIR merge IPs',
        Template       => 'Blank'
    },

    {
        Description    => "SetDomainFromContent",
        Queue          => [ 'Incidents', 'Incident Reports', 'Investigations', 'Countermeasures' ],
        ScripCondition => 'On Correspond',
        ScripAction    => 'RTIR parse message for Domains',
        Template       => 'Blank'
    },
    {
        Description    => "SetDomainFromContent",
        Queue          => [ 'Incidents', 'Incident Reports', 'Investigations', 'Countermeasures' ],
        ScripCondition => 'On Create',
        ScripAction    => 'RTIR parse message for Domains',
        Template       => 'Blank'
    },
    {   Description => "MergeDomains",
        Queue =>
            [ 'Incidents', 'Incident Reports', 'Investigations', 'Countermeasures' ],
        ScripCondition => 'RTIR Merge',
        ScripAction    => 'RTIR merge Domains',
        Template       => 'Blank'
    },
    {   Description    => "On Linking To Incident Copy Domains",
        Queue          => 'Incident Reports',
        ScripCondition => 'RTIR Linking To Incident',
        ScripAction    => 'RTIR merge Domains',
        Template       => 'Blank'
    },

    {
        Description    => "SetCVEFromContent",
        Queue          => [ 'Incidents', 'Incident Reports', 'Investigations', 'Countermeasures' ],
        ScripCondition => 'On Correspond',
        ScripAction    => 'RTIR parse message for CVEs',
        Template       => 'Blank'
    },
    {
        Description    => "SetCVEFromContent",
        Queue          => [ 'Incidents', 'Incident Reports', 'Investigations', 'Countermeasures' ],
        ScripCondition => 'On Create',
        ScripAction    => 'RTIR parse message for CVEs',
        Template       => 'Blank'
    },
    {   Description => "MergeCVEs",
        Queue =>
            [ 'Incidents', 'Incident Reports', 'Investigations', 'Countermeasures' ],
        ScripCondition => 'RTIR Merge',
        ScripAction    => 'RTIR merge CVEs',
        Template       => 'Blank'
    },
    {   Description    => "On Linking To Incident Copy CVEs",
        Queue          => 'Incident Reports',
        ScripCondition => 'RTIR Linking To Incident',
        ScripAction    => 'RTIR merge CVEs',
        Template       => 'Blank'
    },
);

# WARNING: If you change content of the templates, don't forget to
# mention it in the UPGRADING file

@Templates = (
    {   Queue       => 'Countermeasures',
        Name        => 'Autoreply',
        Description => 'Sent when a countermeasure is created',
        Content     => 'RT-Attach-Message: yes
Subject: { $Ticket->Subject }

{ $Transaction->Content }

{ my $output = "";
  my @mailfields = ( "IP", "Netmask", "Port", "Where Blocked" );

  my $CustomFields = $Ticket->QueueObj->TicketCustomFields;
  while ( my $CustomField = $CustomFields->Next ) {
    my $name = $CustomField->Name;
    next unless grep lc $_ eq lc $name, @mailfields;

    my $Values = $Ticket->CustomFieldValues( $CustomField->Id );
    while ( my $Value = $Values->Next ) {
      $output .= $name .": ". $Value->Content ."\n";
    }
  }
  return $output;
}
-------------------------------------------------------------------------
Please include the string:

         [{ $Ticket->SubjectTag } #{ $Ticket->id }]

in the subject line of all future correspondence about this issue. To do so, 
you may reply to this message.

                        Thank you,
                        { $Ticket->QueueObj->CorrespondAddress }',
    },
    {   Queue       => 'Countermeasures',
        Name        => 'CountermeasureRemoved',
        Description => 'Sent when a countermeasure is removed',
        Content     => 'Subject: {$Ticket->Subject}

Countermeasure #{$Ticket->id} was removed.

{ my $output = "";
  my @mailfields = ( "IP", "Netmask", "Port", "Where Blocked" );

  my $CustomFields = $Ticket->QueueObj->TicketCustomFields;
  while ( my $CustomField = $CustomFields->Next ) {
    my $name = $CustomField->Name;
    next unless grep lc $_ eq lc $name, @mailfields;

    my $Values = $Ticket->CustomFieldValues( $CustomField->Id );
    while ( my $Value = $Values->Next ) {
      $output .= $name .": ". $Value->Content ."\n";
    }
  }
  return $output;
}
-------------------------------------------------------------------------
Please include the string:

         [{ $Ticket->SubjectTag } #{$Ticket->id}]

in the subject line of all future correspondence about this issue. To do so, 
you may reply to this message.

                        Thank you,
                        {$Ticket->QueueObj->CorrespondAddress()}',
    },
    {   Queue       => 'Investigations',
        Name        => 'Autoreply',
        Description => 'Sent when an investigation is launched',
        Content     => 'RT-Attach-Message: yes
Subject: {$Ticket->Subject}

{$Transaction->Content()}

-------------------------------------------------------------------------
Please include the string:

         [{ $Ticket->SubjectTag } #{$Ticket->id}]

in the subject line of all future correspondence about this issue. To do so, 
you may reply to this message.

                        Thank you,
                        {$Ticket->QueueObj->CorrespondAddress()}',
    },
);

@Groups = (
    {   Name        => 'DutyTeam',
        Domain      => 'UserDefined',
        Instance    => '',
        Description => 'Duty Team Members',    # loc
    },
);

@ACL = ();
for my $queue ( map { $_->{Name} } @Queues ) {
    foreach my $right ( RT::IR->OwnerAllQueueRights ) {
        push @ACL,
            (
            {   GroupDomain => 'RT::Queue-Role',
                GroupType   => 'Owner',
                Queue       => $queue,
                Right       => $right
            },
            );
    }
}

for my $queue ( map { $_->{Name} } @Queues ) {
    foreach my $right ( RT::IR->DutyTeamAllQueueRights ) {
        push @ACL, {
            GroupId     => 'DutyTeam',      # - principalId
            GroupDomain => 'UserDefined',
            Queue       => $queue,
            Right       => $right
            },

    }
}

push @ACL, map {
    {   Queue       => 'Investigations',
        GroupType   => 'Everyone',
        GroupDomain => 'SystemInternal',

        Right => $_
    }
} RT::IR->EveryoneInvestigationRights();

push @ACL, map {
    {   Queue       => 'Incidents',
        GroupType   => 'Everyone',
        GroupDomain => 'SystemInternal',

        Right => $_
    }
} RT::IR->EveryoneIncidentRights();

push @ACL, map {

    {   GroupType   => 'Everyone',
        GroupDomain => 'SystemInternal',
        Queue       => 'Incident Reports',
        Right       => $_
    }
} RT::IR->EveryoneIncidentReportRights();

push @ACL, map {
    {   GroupType   => 'Everyone',
        GroupDomain => 'SystemInternal',
        Queue       => 'Countermeasures',
        Right       => $_
    }
} RT::IR->EveryoneCountermeasureRights();

push @ACL, (
    {   GroupId     => 'DutyTeam',      # - principalId
        GroupDomain => 'UserDefined',
        Queue       => 0,
        Right       => 'ModifySelf',
    },
    {   GroupId     => 'DutyTeam',            # - principalId
        GroupDomain => 'UserDefined',
        Queue       => 0,
        Right       => 'SeeOwnSavedSearch',
    },
    {   GroupId     => 'DutyTeam',            # - principalId
        GroupDomain => 'UserDefined',
        Queue       => 0,
        Right       => 'AdminOwnSavedSearch',
    },
    {   GroupId     => 'DutyTeam',            # - principalId
        GroupDomain => 'UserDefined',
        Queue       => 0,
        Right       => 'SeeGroupSavedSearch',
    },
    {   GroupId     => 'DutyTeam',            # - principalId
        GroupDomain => 'UserDefined',
        Queue       => 0,
        Right       => 'AdminGroupSavedSearch',
    },
    {   GroupId     => 'DutyTeam',            # - principalId
        GroupDomain => 'UserDefined',
        Queue       => 0,
        Right       => 'SeeOwnDashboard',
    },
    {   GroupId     => 'DutyTeam',            # - principalId
        GroupDomain => 'UserDefined',
        Queue       => 0,
        Right       => 'AdminOwnDashboard',
    },
    {   GroupId     => 'DutyTeam',            # - principalId
        GroupDomain => 'UserDefined',
        Queue       => 0,
        Right       => 'SeeGroupDashboard',
    },
    {   GroupId     => 'DutyTeam',            # - principalId
        GroupDomain => 'UserDefined',
        Queue       => 0,
        Right       => 'AdminGroupDashboard',
    },
    {   GroupId     => 'DutyTeam',            # - principalId
        GroupDomain => 'UserDefined',
        Queue       => 0,
        Right       => 'LoadSavedSearch',
    },
    {   GroupId     => 'DutyTeam',            # - principalId
        GroupDomain => 'UserDefined',
        Queue       => 0,
        Right       => 'AdminSavedSearch',
    },
);

# Predefined searches

@SavedSearches = (
    { Name => 'New unlinked Incident Reports',
      Description => 'New unlinked Incident Reports', # loc
      Content => {
          ExtraQueryParams => 'RTIR',
          Format           => q{'<b><a href="__RTIRTicketURI__">__id__</a></b>/TITLE:#',}
              . q{'<b><a href="__RTIRTicketURI__">__Subject__</a></b>/TITLE:Subject',}
              . q{Requestors,OwnerName,DueRelative,QueueName,Take},
          Order             => 'ASC|ASC|ASC|ASC',
          OrderBy           => 'Due',
          Query             => 'Lifecycle = \'incident_reports\' AND Status = \'new\'',
          RTIR              => 1,
          RTIRSearchEnabled => 1,
          RowsPerPage       => 10,
      },
    },
    { Name => 'My most due incidents',
      Description => 'Most due incidents I own', # loc
      Content => {
          ExtraQueryParams => 'RTIR',
          Format           => q{'<b><a href="__RTIRTicketURI__">__id__</a></b>/TITLE:#',}
              . q{'<b><a href="__RTIRTicketURI__">__Subject__</a></b>/TITLE:Subject',}
              . q{DueRelative, OwnerName, __Priority__,}
              . q{'UnreadMessages/TITLE:Updates'},
          Order             => 'ASC|DESC|ASC|ASC',
          OrderBy           => 'Due|Priority',
          Query             => 'Lifecycle = \'incidents\' AND Status = \'__Active__\' AND Owner = \'__CurrentUser__\'',
          RTIR              => 1,
          RTIRSearchEnabled => 1,
          RowsPerPage       => 10,
      },
    },
    { Name => 'Most due unowned incidents',
      Description => 'Most due unowned incidents', # loc
      Content => {
          ExtraQueryParams => 'RTIR',
          Format           => q{'<b><a href="__RTIRTicketURI__">__id__</a></b>/TITLE:#',}
              . q{'<b><a href="__RTIRTicketURI__">__Subject__</a></b>/TITLE:Subject',}
              . q{DueRelative, OwnerName, __Priority__,}
              . q{'UnreadMessages/TITLE:Updates'},
          Order             => 'ASC|DESC|ASC|ASC',
          OrderBy           => 'Due|Priority',
          Query             => 'Lifecycle = \'incidents\' AND Status = \'__Active__\' AND Owner = \'Nobody\'',
          RTIR              => 1,
          RTIRSearchEnabled => 1,
          RowsPerPage       => 10,
      },
    },
    { Name => 'Most due incidents',
      Description => 'Most due incidents', # loc
      Content => {
          ExtraQueryParams => 'RTIR',
          Format           => q{'<b><a href="__RTIRTicketURI__">__id__</a></b>/TITLE:#',}
              . q{'<b><a href="__RTIRTicketURI__">__Subject__</a></b>/TITLE:Subject',}
              . q{DueRelative, OwnerName, __Priority__,}
              . q{'UnreadMessages/TITLE:Updates'},
          Order             => 'ASC|DESC|ASC|ASC',
          OrderBy           => 'Due|Priority',
          Query             => 'Lifecycle = \'incidents\' AND Status = \'__Active__\'',
          RTIR              => 1,
          RTIRSearchEnabled => 1,
          RowsPerPage       => 10,
      },
    },
);

for my $cf (@CustomFields) {
    push @ACL,
        (
        {   GroupId     => 'DutyTeam',
            GroupDomain => 'UserDefined',
            CF          => $cf->{Name},
            Queue       => $cf->{Queue},
            Right       => 'SeeCustomField',
        },
        {   GroupId     => 'DutyTeam',
            GroupDomain => 'UserDefined',
            CF          => $cf->{Name},
            Queue       => $cf->{Queue},
            Right       => 'ModifyCustomField',
        },
        );
}

@Classes = (
    {
        Name        => 'Templates',
        Description => 'Response templates',
        ApplyTo     => [ map { $_->{Name} } @Queues ],
    },
    {
        Name => 'Incidents Processes',
        Description => 'Processes to be followed in the event of an incident',
        ApplyTo => [],
    }
);

@Articles = (
    {
        Name => 'Spam Process',
        Summary => 'This is the summary of the process for handling spam',
        CustomFields => [
            {
                CustomField  => 'Content',
                Content => 'This is the content of the process for handling spam',
            },
        ],
        Class => 'Incidents Processes',
    },
    {
        Name => 'System Compromise Process',
        Summary => 'This is the summary of the process for handling system compromise',
        CustomFields => [
            {
                CustomField  => 'Content',
                Content => 'This is the content of the process for handling system compromise',
            },
        ],
        Class => 'Incidents Processes',
    },
    {
        Name => 'Query Process',
        Summary => 'This is the summary of the process for handling queries',
        CustomFields => [
            {
                CustomField  => 'Content',
                Content => 'This is the content of the process for handling queries',
            },
        ],
        Class => 'Incidents Processes',
    },
    {
        Name => 'Scan Process',
        Summary => 'This is the summary of the process for handling scans',
        CustomFields => [
            {
                CustomField  => 'Content',
                Content => 'This is the content of the process for handling scans',
            },
        ],
        Class => 'Incidents Processes',
    },
    {
        Name => 'Denial of Service Process',
        Summary => 'This is the summary of the process for handling denial of service',
        CustomFields => [
            {
                CustomField  => 'Content',
                Content => 'This is the content of the process for handling denial of service',
            },
        ],
        Class => 'Incidents Processes',
    },
    {
        Name => 'Piracy Process',
        Summary => 'This is the summary of the process for handling piracy',
        CustomFields => [
            {
                CustomField  => 'Content',
                Content => 'This is the content of the process for handling piracy',
            },
        ],
        Class => 'Incidents Processes',
    }
);

@Final = (
    sub {
        $| = 1;
        my $CurrentUser = RT::CurrentUser->new();
        $CurrentUser->LoadByName('RT_System');

        require RT::Class;
        my $class = RT::Class->new($CurrentUser);
        $class->Load('Templates');

        require RT::Article;
        my $response = RT::CustomField->new($CurrentUser);
        $response->Load('Response');
        unless ($response->Id
            and $response->LookupType eq RT::Article->CustomFieldLookupType )
        {
            $RT::Logger->info("Creating 'Response' Article custom field.");
            my ( $id, $msg ) = $response->Create(
                Name        => 'Response',
                Type        => 'Text',
                MaxValues   => 1,
                Description => 'Response to be inserted into the ticket',
                LookupType  => RT::Article->CustomFieldLookupType,
            );
            die $msg unless $id;
        }

        $response->AddToObject($class);

        my @skips = ( "Name", "Summary", "CF-Title-" . $response->Id );

        my $content = RT::CustomField->new($CurrentUser);
        $content->LoadByName( Name => 'Content', LookupType => RT::Article->CustomFieldLookupType );
        if ( $content->Id && ( $content->IsGlobal || $content->IsAdded( $class->Id ) ) ) {
            push @skips, "CF-Title-" . $content->Id, "CF-Value-" . $content->Id;
        }

        $class->SetAttribute( Name => "Skip-$_", Content => 1 ) for @skips;

        my $group = RT::Group->new($CurrentUser);
        $group->LoadUserDefinedGroup("DutyTeam");
        die "Can't load group" unless $group->Id;

        (my $ret, $msg) = $group->PrincipalObj->GrantRight( Right => 'SeeCustomField', Object => $class );
        die "Could not grant DutyTeam 'SeeCustomField' on class 'Templates': $msg" unless $ret;

        $group->PrincipalObj->GrantRight( Right => $_, Object => $response )
            for qw/SeeCustomField ModifyCustomField/;
        $group->PrincipalObj->GrantRight( Right => $_, Object => $class )
            for
            qw/AdminClass AdminTopics CreateArticle ModifyArticle ModifyArticleTopics SeeClass ShowArticle ShowArticleHistory DeleteArticle/;
        $group->PrincipalObj->GrantRight(
            Right  => ShowArticlesMenu,
            Object => RT->System
        );

    },
    sub {
        # The last 4 saved searches should be the ones added above.
        # Don't load by name since there could be other existing searches with
        # these names.
        my ($new_reports, $user_incidents, $nobody_incidents, $due_incidents);
        my $saved_searches = RT::SavedSearches->new(RT->SystemUser);
        $saved_searches->UnLimit;
        $due_incidents = $saved_searches->Last;

        $new_reports = RT::SavedSearch->new(RT->SystemUser);
        $new_reports->Load( $due_incidents->Id - 3 );

        $user_incidents = RT::SavedSearch->new(RT->SystemUser);
        $user_incidents->Load( $due_incidents->Id - 2 );

        $nobody_incidents = RT::SavedSearch->new(RT->SystemUser);
        $nobody_incidents->Load( $due_incidents->Id - 1 );

        my $rtir_dashboard = {
            Elements => [
                {
                    Layout   => 'col-md-8,col-md-4',
                    Elements => [
                        [
                        {
                            portlet_type => 'search',
                            id           => $new_reports->Id,
                            description  => 'Ticket: ' . $new_reports->Description,
                        },
                        {
                            portlet_type => 'search',
                            id           => $user_incidents->Id,
                            description  => 'Ticket: ' . $user_incidents->Description,
                        },
                        {
                            portlet_type => 'search',
                            id           => $nobody_incidents->Id,
                            description  => 'Ticket: ' . $nobody_incidents->Description,
                        },
                        {
                            portlet_type => 'search',
                            id           => $due_incidents->Id,
                            description  => 'Ticket: ' . $due_incidents->Description,
                        },
                        ],
                        [
                        {
                            portlet_type => 'component',
                            component    => '/RTIR/Elements/WorkWithConstituency',
                            description  => '/RTIR/Elements/WorkWithConstituency',
                            path         => '/RTIR/Elements/WorkWithConstituency',
                        },
                        {
                            portlet_type => 'component',
                            component    => '/RTIR/Elements/QueueSummary',
                            description  => '/RTIR/Elements/QueueSummary',
                            path         => '/RTIR/Elements/QueueSummary',
                        },
                        ]
                    ],
                }
            ],
        };

        my $dashboard = RT::Dashboard->new( RT->SystemUser );
        my ( $ret, $msg ) = $dashboard->Create(
            Name        => 'RTIRDefaultDashboard',
            Description => 'RTIR Default Dashboard',
            PrincipalId => RT->SystemUser->PrincipalId,
            Content => $rtir_dashboard,
        );

        if ( !$ret ) {
            RT->Logger->error("Couldn't create RTIRDefaultDashboard: $msg");
        }

        if ( $ret ) {
            ( $ret, $msg ) = RT->System->SetAttribute(
                'Name'        => 'RTIRDefaultDashboard',
                'Description' => 'RTIR Default Dashboard',
                'Content'     => $dashboard->Id,
            );
            if ( !$ret ) {
                RT->Logger->error("Couldn't set RTIRDefaultDashboard: $msg");
            }
        }
    },
    sub {
        my $class = RT::Class->new( RT->SystemUser );
        my ($ok, $msg) = $class->Load('Incidents Processes');
        RT->Logger->error("Unable to load class Incidents Processes: $msg") unless $ok;

        my $content = RT::CustomField->new( RT->SystemUser );
        $content->LoadByName( Name => 'Content', LookupType => RT::Article->CustomFieldLookupType );

        my @skips = ( "Name", "Summary", "LinkToTicket", $content->Id ? "CF-Title-" . $content->Id : () );
        $class->SetAttribute(Name => "Skip-$_", Content => 1) for @skips;

        my $group = RT::Group->new( RT->SystemUser );
        $group->LoadUserDefinedGroup("DutyTeam");
        die "Can't load group" unless $group->Id;
        $group->PrincipalObj->GrantRight( Right => $_, Object => $class )
            for qw/ShowArticle SeeCustomField AdminClass AdminTopics CreateArticle ModifyArticle ModifyArticleTopics SeeClass ShowArticleHistory DeleteArticle/;
        }
);
