#!/usr/bin/perl -w
#==============================================================================
# Copyright and license info is available in the LICENSE file included with
# the Server Deployment Package (SDP), and also available online:
# https://swarm.workshop.perforce.com/projects/perforce-software-sdp/view/main/LICENSE
#------------------------------------------------------------------------------
#
# See documentation at the end.

#==============================================================================
# Environment Setup, Library Includes, and Prototypes
#==============================================================================
require 5.010;
use strict;
use File::Basename;

BEGIN
{
    $main::ThisScript = basename($0);
    $main::ThisScript =~ s/\.exe$/\.pl/i;
    $main::VERSION = "1.0.2";
}

sub usage (;$);

#==============================================================================
# Command Line Parsing
#==============================================================================
# As a trigger script not called by humans directly, usage errors are unlikely.
die ("Usage Error.  See script docs.") if ($#ARGV != 0 );

usage() if ($ARGV[0] eq '-h');
usage('man') if ($ARGV[0] eq '-man');

#==============================================================================
# Main Program
#==============================================================================

my $JobSpecFile=$ARGV[0];
my $NewJobSpecFile="$JobSpecFile.new";
my $Project = 'Unset';
my $HighJobNumKey = 'Unset';
my $HighJobNum = 'Unset';
my $JobPrefixKey = 'Unset';
my $JobPrefix = 'Unset';
my $JobName = 'Unset';
my $DocOutput;
my $DoUpdate = 1;

open (JOB, "<$JobSpecFile") or die ("Trigger Script Error: $main::ThisScript: Failed to open job spec file [$JobSpecFile]: $!\n");

open (NEWJOB, ">$NewJobSpecFile") or die ("Trigger Script Error: $main::ThisScript: Failed to create new job spec file [$NewJobSpecFile]: $!\n");

while (<JOB>) {
   if (/^Job:\s+/) {
      if (/^Job:\s+new$/) {
         # Avoiding writing the 'Job:' field to the new job file, since we don't yet know
         # what the value should be.
         next;
      } else {
         $DoUpdate = 0;
         last;
      }
   }

   if (/^Project:/) {
      $Project = $_;
      $Project =~ s/^Project:\s*//;
      $JobPrefixKey = "JobPrefix-$Project";
      $JobPrefix = `p4 counter $JobPrefixKey`;
      chomp $JobPrefix;
      if ($JobPrefix eq "0" or $JobPrefix eq "") {
         $DoUpdate = 0;
         last;
      }
      $HighJobNumKey = "HighJobNum-$JobPrefix";
      # Use 'p4 counter -i' to simultaneously access and increment
      # the counter value.
      $HighJobNum = `p4 counter -i $HighJobNumKey`;
      chomp $HighJobNum;

      $JobName = $JobPrefix . '-' . $HighJobNum;

      print NEWJOB "Job:\t$JobName\n\n";
      
   }
   print NEWJOB;
}

close (JOB);
close (NEWJOB);

$DoUpdate = 0 if ($Project eq 'Unset');

if ($DoUpdate) {
   rename ($NewJobSpecFile, $JobSpecFile) or
      die ("Trigger Script Error: $main::ThisScript: Failed to update job spec file: $!");
} else {
   unlink ($NewJobSpecFile);
}

exit 0;

#==============================================================================
# Local Functions
#==============================================================================
#
#------------------------------------------------------------------------------
# Subroutine: usage (required function)
#
# Description:
#   Display usage message and exit.
#
# Input:
# $1 - Usage Style, either man for man page or null, indicating only a usage
# syntax message is desired.
#
# Output: Message
#
# Return Values: Program Exits with status 1.
#
# Side Effects: Program terminates.
#------------------------------------------------------------------------------
sub usage (;$)
{
    my $style  = shift || "h";
    my $scriptDocFile = $main::ThisScript;

    # Be sure to keep the short "syntax only" version of the usage message
    # in sync with the info in POD style at the top of the script.
    if ($style eq "man")
    {
        $scriptDocFile =~ s/\.(pl|exe)$/\.html/i;
        $scriptDocFile = "$scriptDocFile.html" unless ($scriptDocFile =~ /\.html$/);

        if ( -r $main::ThisScript)
        {
            $DocOutput = `perldoc $main::ThisScript`;
            print $DocOutput;
            exit (1);
        }

        # If perldoc.exe or the  source *.pl script isn't available,
        # display a message indicating the existence of HTML docs.
        print "
    $main::ThisScript v$main::VERSION

    See $scriptDocFile for more info.\n\n";
        exit 1;
    } else
    {
        print "
$main::ThisScript v$main::VERSION\n
Usage from Trigger Table:

Triggers:
\tJobIncrement form-in job \"/p4/common/bin/triggers/JobIncrement.pl \%formfile\%\"

 OR, command line usage:
   $main::ThisScript {-h|-man}
";
    }

    exit 1;
}


=head1 NAME

JobIncrement.pl - Trigger to increment jobs with custom names.

=head1 VERSION

1.0.2

=head1 SYNOPSIS

Enable this as a form-in trigger on the job form, for example:

=over 4

Triggers:

=over 4

C<JobIncrement form-in job "/p4/common/bin/triggers/JobIncrement.pl %formfile%">

=back

=back

OR

C<JobIncrement.pl {-h|-man}>

=head1 DESCRIPTION

=head2 Overview

The default job naming convention with Perforce Jobs has an auto-increment
feature, so that if you create job with a 'Job:' field value of 'new',
it will be changed to jobNNNNNN, with the six-digit value being
automatically incremented.

Perforce jobs also support custom job naming, e.g. to name jobs PROJX-123,
where the name itself is more meaningful.  But if you use custom job names,
you forego the convenience of automatic generation of a new job number.  Now
typically, if the default job naming feature isn't used, it's because new
issues originate in an external issue tracking, so there's no need for
incrementing by Perforce; the custom job names just mirror the value in the
external system.

This script is aims to make it easier to use custom job names with Perforce
even when there is no external issue tracker integration, by providing the
ability to generate new job names with automatically incremented numbers
on a per-project basis.

=head2 Concepts

=over 4

=item 1.

Job Prefix

The 'Project:' field in the Jobspec has a 'select' field with pre-defined
values for project names.  Projects desiring to use custom jobs names
will define a counter named JobPrefix-<project_name>.  The value
will be a tag name, a short form of the project name, to be used as a
prefix for job names.  For example, a project named
joe_schmoe-wicked-good-thing might have a prefix of WGT.  Jobs will be
named WGT-1, WGT-2, etc.  By convention, job prefixes are comprised only
of uppercase letters, matching the pattern ^[A-Z]$.  No spaces, commas,
dashes, underbars, etc. allowed. (There is no mechanicm for mechanical
enforcement of this convention, nor any needed, as tags are defined and
created by Perforce Admins).

To define a prefix for a project, an admin define a value for the
appropriate counter, e.g. by doing:

C<p4 counter JobPrefix-joe_schmoe-wicked-good-thing WGT>

To see what job prefixes are currently defined, you can do:

C<p4 counters -e JobPrefix-*>

=item 2.

High Number Counter

For projects with defined tags, there will also be a high number counter
tracking the highest numbered job with a give prefix.  This counter is
created automatically and maintained by this script.

=item 3.

JobIncrement trigger (this script).

This trigger script fires as a 'form-in' trigger on job forms, i.e. it
fires on jobs that are on their way into the server.  If 'Job:' field
value is 'new' and the 'Project:' field value has an associated JobPrefix
counter, then the name of the job is determined and set by incrementing the
High Number counter, ultimately replacing the value 'new' with something
like WGT-201 before it ever gets to the server.  If no High Number counter
exists for the project, it gets set to '1'.

=back

=head1 ARGUMENTS

=head2 -h|-man

Display a usage message.  The -h display a short synopsis only, while -man displays this message.

=head1 RETURN STATUS

Zero indicates normal completion, Non-Zero indicates an error.

=cut
