#!/usr/bin/perl

use Date::Parse;
use POSIX qw(strftime);

our $DEBUG = 0;
our $DRYRUN = 0;

our $DOER = 'quentin@NOT-BACKWARD.MIT.EDU';
our $SELF = "/afs/athena.mit.edu/contrib/scripts/deploydev/updates/fix-scripts-version-django.pl";

sub sanitizeDate($) {
  my $date = shift;
  if (str2time($date)) {
    return strftime("%F %T %z", localtime str2time($date));
  } else {
    return $date;
  }
}

sub findIndex($@) {
  my ($needle, @haystack) = @_;
  foreach my $i (0..$#haystack) {
    if ($haystack[$needle] eq $needle) {
      return $i;
    }
  }
  return undef;
}

open(LOG, ">>", "update-scripts-version.log") or warn "Couldn't open log for writing";

open(SUCCESS, ">>", "success");
open(FAILURE, ">>", "failed");

foreach my $file (@ARGV) {
  unless (open(OLD, "<", $file)) { warn "Can't open $file for reading"; next; }
  my @lines = <OLD>;
  chomp @lines;
  close(OLD);
  my $date = strftime("%F %T %z", localtime);
  if ($lines[-1] =~ m|/deploy$|) {
    if ($lines[-2] =~ m|turbogears\.tar\.gz$|) {
      push @lines, "", $date, $DOER, $SELF;
      push @lines, "/afs/athena.mit.edu/contrib/scripts/deploy/turbogears-1.0.8";
    } elsif ($lines[-2] =~ m|django\.tar\.gz$|) {
      push @lines, "", $date, $DOER, $SELF;
      push @lines, "/afs/athena.mit.edu/contrib/scripts/deploy/django-0.1-scripts";
    }
  } else {
    warn "ERROR: Nothing to do with $file";
    next;
  }
  my $out = join("\n", @lines);
  unless ($DRYRUN) {
    my $success = 1;
    unless (rename($file, $file.".oldversion")) {
      warn "ERROR: Can't move $file out of the way";
      $success = 0;
    }
    unless (open(OUT, ">", $file)) {
      warn "ERROR: Can't open $file for writing";
      $success = 0;
    }
    print OUT $out;
    close(OUT);
    if ($success) { print SUCCESS "$file\n"; }
    else { print FAILURE "$file\n"; }
    print LOG "$file $package-$version\n";
  }
  print $out if $DEBUG;
}

close(LOG);
