#!/usr/bin/perl -w
########################################################################
# increment-version
#
# Increment a product's version in its own product_deps file and
# optionally update dependency listings in other packages to match.
########################################################################
use strict;

use Cwd qw(chdir :DEFAULT);
use File::Basename;
use File::Find;
use FileHandle;
use Getopt::Long;
use Pod::Usage;

Getopt::Long::Configure(qw(no_ignore_case bundling require_order));

my $options = {};
my %bumped_versions = ();
my $wanted_version;

GetOptions($options,
           "debug|d",
           "client-dir|c=s@",
           "dry-run|n",
           "help|h|?",
           "M|major", \&set_mode,
           "m|minor", \&set_mode,
           "p|patch", \&set_mode,
           "s|set-version=s", \&set_mode,
           "tag",
           "verbose|v",
           "u|micro", \&set_mode,
           "update-only|U=s", \&mark_for_update
) or pod2usage(-exitval => 2);

$options->{help} and pod2usage(-exitval => 1, -verbose => 3);

$options->{"dry-run"} and report("Dry run: no actual changes made!");

if (scalar keys %bumped_versions) { # update-only.
  $options->{"client-dir"} = ( "." )
    unless exists $options->{"client-dir"};
} else { # Normal mode
  if (not defined $options->{mode}) {
    error("Expected exactly one mode specification.");
    pod2usage(-exitval => 2);
  }
  foreach my $loc ((scalar @ARGV)?@ARGV:(".")) {
    inc_version($loc);
  }
}

update_clients();

maybe_commit_and_tag();

1;

sub set_mode {
  my ($opt, $arg) = @_;
  if (!exists $options->{mode} or
      ($options->{mode} eq $opt and $opt eq "U")) {
    $options->{mode} = shift;
    $wanted_version = $arg if $opt eq "s";
  } else {
    error("Expected exactly one mode specification.");
    pod2usage(-exitval => 2);
  }
}

sub mark_for_update {
  my ($cetpackage, $version, $loc) = @_;
  if ($cetpackage eq "update-only") { # Argument processing.
      ($cetpackage, $version) = split /,/, $version;
    unless ($cetpackage and $version) {
      error("mark_for_update: bad package / version $cetpackage / $version.");
      return 1;
    }
    $version =~ s&^v&&;   # Strip any leading "v."
  }
  $bumped_versions{$cetpackage} = { version => $version };
  $bumped_versions{$cetpackage}->{loc} = $loc if $loc;
}

sub info {
  print STDERR "INFO: ", @_, "\n"
    if $options->{verbose};
}

sub report {
  print STDERR "INFO: ", @_, "\n";
}

sub error {
  print STDERR "ERROR: ", @_, "\n";
}

sub inc_version {
  my $loc = shift;
  -f "$loc/ups/product_deps" or return;
  my $deps_file = "$loc/ups/product_deps";
  open(IN, $deps_file) or
    do { error("Unable to open file \"$deps_file\" for read."); exit(1); };
  my $tmp = `mktemp /tmp/increment-version.XXXXXXXXXX`;
  chomp $tmp;
  $tmp or do { error("Unable to get temporary file.\n"); exit(1); };
  open(OUT, ">$tmp") or
    do { error("Unable to open temporary file for write."); exit(1); };
  my ($stem, $cetpackage, $version, @v, $new_version);
  while (<IN>) {
    ($stem, $cetpackage, $version, @v) =
      (m&^(\s*parent\s+(\S+)\s+v)((\d+)_(\d+)(?:_(\d+)(?:(_?(?:pre|rc|p|alpha|a|beta|b)?\d+))?)?(.*))$&)
        unless $cetpackage;
    do {print OUT; next;} unless scalar @v;
    my $tail = pop @v;
    $tail =~ s&^\S*&&; # Remove super-micro version.
    if ($options->{mode} eq "M") {
      ++$v[0];
      defined $v[1] and $v[1] = 0;
      defined $v[2] and $v[2] = 0;
      undef $v[3];
    } elsif ($options->{mode} eq "m") {
      ++$v[1];
      defined $v[2] and $v[2] = 0;
      undef $v[3];
    } elsif ($options->{mode} eq "u") {
      if (defined $v[2]) {
        ++$v[2];
      } else {
        $v[2] = 1;
      }
      undef $v[3];
    } elsif ($options->{mode} eq "p") {
      if (defined $v[3]) {
        my ($x, $ver) = ($v[3] =~ m&^(\D*)(\d*)$&);
        ++$ver if defined $ver;
        $v[3] = sprintf("%s%02d", $x || "", $ver || 1);
      } else {
        $v[3] = "_01";
      }
    }
    if ($wanted_version) {
      $new_version = $wanted_version;
      $new_version =~ s&^v&&;   # Strip any leading "v."
    } else {
      $new_version = $v[0];
      defined $v[1] and $new_version .= sprintf("_%02d", $v[1]);
      defined $v[2] and $new_version .= sprintf("_%02d", $v[2]);
      defined $v[3] and $new_version .= $v[3];
    }
    report "$cetpackage v$version -> v$new_version.";
    print OUT "$stem$new_version", $tail || "", "\n";
    undef @v;
  }
  close(IN);
  close(OUT);
  if (system("diff -qwu \"$deps_file\" \"$tmp\" >/dev/null 2>&1")) {
    unless ($options->{"dry-run"}) {
      if (system("cp", "$tmp", "$deps_file")) {
        ERROR("Updating $deps_file from $tmp: $!");
        exit(1);
      }
    }
    mark_for_update($cetpackage, $new_version, $loc);
  }
  unlink($tmp) unless $options->{debug};
}

sub maybe_new_version {
  my $cetpackage = shift;
  if (exists $bumped_versions{$cetpackage}) {
    return $bumped_versions{$cetpackage}->{version};
  } else {
    return;
  }
}

sub update_one_client {
  my $file_to_update = shift;
  open(IN, $file_to_update) or die "Unable to open file \"$file_to_update\" for read.";
  my $tmp = `mktemp /tmp/increment-version.XXXXXXXXXX`;
  chomp $tmp;
  $tmp or
    do { error("Unable to get temporary file."); exit(1); };
  open(OUT, ">$tmp") or
    do { error("Unable to open temporary file for write."); exit(1); };
  my $in_prods;
  my ($stem, $cetpackage, $version, @v, $new_version);
  while (<IN>) {
    chomp;
    m&^\s*(?:#|$)& and next;
    ($stem, $cetpackage, $version, @v) =
      (m&^(\s*parent\s+(\S+)\s+v)((\d+)_(\d+)(?:_(\d+)(?:p(\d+))?)?(.*))$&)
        unless $cetpackage;
    m&^\s*product\s+version& and do { $in_prods = 1; next; };
    $in_prods and do {
      my ($stem, $found_prod, $found_version) =
        (m&^((?:\s*only_for_build)?\s*(\S+)\s+v)(\S+)&);
      if ($found_prod and $found_version) {
        my $new_version = maybe_new_version($found_prod);
        if ($new_version and $found_version ne $new_version) {
          report "Updating ${cetpackage}'s use of $found_prod from $found_version to $new_version in ",
            dirname($File::Find::dir),
              ".";
          s&^\Q$stem$found_version&${stem}$new_version&;
        }
      } else {
        undef $in_prods;
      }
    };
  }
  continue {
    print OUT "$_\n";
  }
  close(IN);
  close(OUT);
  if (system("diff -qwu \"$file_to_update\" \"$tmp\" >/dev/null 2>&1")) {
    unless ($options->{"dry-run"}) {
      if (system("cp", "$tmp", "$file_to_update")) {
        error("Updating $file_to_update from $tmp: $!");
        exit(1);
      }
    }
  }
  unlink($tmp) unless $options->{debug};
}

sub update_clients {
  File::Find::find({wanted => \&wanted, follow => 1}, @{$options->{"client-dir"}})
      if (defined $options->{"client-dir"} and scalar keys %bumped_versions);
}

sub wanted {
    my ($dev,$ino,$mode,$nlink,$uid,$gid);

    (($dev,$ino,$mode,$nlink,$uid,$gid) = lstat($_)) and
      $File::Find::name =~ /^.*\/ups\/product_deps\z/s and
        update_one_client($_);
}

sub maybe_commit_and_tag {
  return unless $options->{tag};
  foreach my $cetpackage (keys %bumped_versions) {
    my $loc = $bumped_versions{$cetpackage}->{loc} or next;
    my $cmd =
      sprintf("pwd; cd \"%s\" && git commit -m 'Bump version to %s' ups/product_deps && git tag -fam 'Bump version for release' v%s",
              $loc,
              $bumped_versions{$cetpackage}->{version},
              $bumped_versions{$cetpackage}->{version}
             );
    if ($options->{"dry-run"}) {
      report("Would tag package $cetpackage at version ",
             $bumped_versions{$cetpackage}->{version},
             " in $loc.");
    } elsif (system($cmd) != 0) {
      error("Unable to commit and tag update to $cetpackage at version ",
            $bumped_versions{$cetpackage}->{version},
            " in $loc.");
    }
  }
}

__END__

=pod

=head1 NAME

increment-version: Increment the current version of a cetmodules-using package.

=head1 SYNOPSIS

B<increment-version> I<mode> [I<options>] [--] [I<package-loc>+]

B<increment-version>  B<--help> | B<-h> | B<-?>

I<mode>: [ B<-M> | B<--major>] | [ B<-m> | B<--minor> ] |
      [ B<-u> | B<--micro> ] | [ B<-p> | B<--patch> ] |
      [ B<--update-only> I<package>,I<version> |
        B<-U> I<package>,I<version> ]

I<options>: [ B<--client-dir> I<package-client-search-path> |
           B<-c> I<package-client-search-path> ]+ |
         [ B<--dry-run> | B<-n> ] |
         [ B<--tag> ] |
         [ B<--verbose> | B<-v> ]

Options marked with B<+> are repeatable and cumulative.

Exactly one I<mode> specification is expected, although B<-U> may be
used several times to specify multiple package/version pairs to update
the references thereto.


=head1 DESCRIPTION

I<increment-version> will increment the current version of a
cetmodules-using package. Optionally find all other packages where
said package is listed as a dependency and update the required version.


=head2 ARGUMENTS

=over

=item I<package-loc>

Path to top directory of package whose version should be bumped.

=back

=head2 Modes

Precisely one mode type should be specified (although -U may be
specified multiple times).

=over

=item B<-M>

=item B<--major>

Increment the major version number, zeroing all used subordinate version
designators.


=item B<-m>

=item B<--minor>

Increment the minor version number, zeroing all used subordinate version
designators.


=item B<-u>

=item B<--micro>

Increment the micro version number, resetting any patch number.


=item B<-p>

=item B<--patch>

Increment the patch number.


=item B<--update-only> I<package>,I<version>

=item B<-U> I<package>,I<version>

Do not increment any version numbers; simply navigate the directories
specified with the B<--client-dir> option (or ./ if not specified) to update
any references to the named package(s) to use the specified version(s)
thereof.

=back

=head2 OPTIONS

=over

=item B<--client-dir> I<package-client-search-path>

=item B<-c> I<package-client-search-path>

Specify a directory to search for I<product_deps> files in which to
update the set-up versions of the updated prodoct(s); or those of
products specified with B<-U>.


=item B<--debug>

=item B<-d>

Debug mode: leave temporary files available.


=item B<--dry-run>

=item B<-n>

Do not actually update anything: just say what would be done.


=item B<--tag>

Commit changes to product_deps and tag all updated packages with their
new versions.


=item B<--verbose>

=item B<-v>

Be more chatty.


=back

=cut
