#!perl -w

# Copyright (C) 1997 Capella Computers Ltd.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

# :FILE:
# Undo end of working on a job.

use strict;
use English;
use P4;

# Takes (optional) job id.
sub usage {
    P4::crash("Usage: p4weu [<job>]");
}

# Parse command line.
my $job;
if ($#ARGV < 0) {
    $job = P4::current_job();
} elsif ($ARGV[0] eq '-h') {
    usage();
} elsif ($ARGV[0] =~ /^\d+$/) {
    $job = shift(@ARGV);
}
if ($#ARGV >= 0) {
    usage();
}

# Lock depot to avoid race conditions
P4::lock('depot', 'p4weu');

# Obtain the job record.
my %record = P4::job_record($job);

# Verify pre-conditions. Note that we allow the developer to
# resume work on failed jobs (of course) but also for OK jobs.
P4::verify_job_status($job, \%record, 'review', 'pass', 'fail');
my $user = P4::current_user();
P4::verify_job_user($job, \%record, $user);
P4::verify_job_development_client($job, \%record, P4::current_client());

# This helps in case something goes wrong.
$record{status} = '_work';
P4::update_job($job, \%record);

# Create the change for continuing work on this branch.
my $retry = $record{retry};
my $change =
	P4::create_change($user, "Re-submit work on $job-$retry by $user.");

# This enables tracking job history.
P4::create_fix($change, $job);

# Remove all locks held by this job.
my %locked_files = P4::locked_files();
my ($locked_file, $locking_job);
while (($locked_file, $locking_job) = each(%locked_files)) {
    if ($locking_job eq $job) {
	delete($locked_files{$locked_file});
    }
}
P4::lock_files(\%locked_files);

# Update the job record with the change number, and set its status to 'work'
# to indicate it is now safe to work with. Remove the reviwer name, if any,
# since the new work will invalidate the review results.
$record{dev_chg} = $change;
$record{status} = 'work';
$record{reviewer} = '-';
P4::update_job($job, \%record);

# Release obtained locks.
P4::unlock();

# Notify caller.
print "Work on job $job (attempt #$retry) by $user has resumed.\n";

# Be nice.
1;