#!/usr/bin/env perl
# IBM(c) 2007 EPL license http://www.eclipse.org/legal/epl-v10.html

#require 'open3.pl';

#This script is a modified version of mtime to be used as part of a sensor in the
#software managemnent system. This PERL script goes and finds the latest changed file via mtime
# It recurses the directory structure starting with the directory passed in via the command line
# (directory routine) and checks each file.
#
# Result is put to stdout

$mtime    = 0;
$startdir = @ARGV[0];
chomp($startdir);

if (-d $startdir) { #directory
  &directory("/", *mtime);
}
elsif (-f $startdir) {   #file
  my ($dv, $in, $m, $nl, $u, $g, $rd, $siz, $at, $mtime1) = stat($startdir);
  $mtime = $mtime1;
}
else { exit 1; }    #not a recognized format

print $mtime;
exit 0;

#
# directory
#
# Goes through directory tree to find files we need to pay attention too.
# Each file is checked for mtime.
#
sub directory
{
  local ($dir, *mtime, $nlink) = @_;
  local ($dev, $ino, $mode, $subcount, $dirtry, $namedirtry, $name1, $name,
         $dir1, $mtime1, $dv, $in, $m, $nl, $u, $g, $rd, $siz, $at);

  ($dev, $ino, $nlink) = stat($dir) unless $nlink;

  $dirtry = $startdir;
  $dirtry .= $dir;

  $dir1 = substr($dir, 1);

  opendir(DIR, $dirtry);

  local (@filenames) = readdir(DIR);

  if ($nlink == 2)  {
    for (@filenames)  {
      next if $_ eq '.';
      next if $_ eq '..';
      #
      # Check to see if the mtime of this file is later than the current mtime
      #
      $name  = "$dir/$_";
      $name1 = "$dir1/$_";
      $name2 = "/$startdir/$name1";

      ($dv, $in, $m, $nl, $u, $g, $rd, $siz, $at, $mtime1) = stat($name2);

      if ($mtime1 > $mtime)  {
        $mtime = $mtime1;
      }
    }
  }
  else {
    $subcount = $nlink - 2;
    for (@filenames)  {
      next if $_ eq '.';
      next if $_ eq '..';

      #
      # Check to see if the mtime of this file is later than the current mtime
      #

      $name  = "$dir/$_";
      $name1 = "$dir1/$_";
      $name2 = "/$startdir/$name1";

      ($dev, $ino, $m, $nl, $u, $g, $rd, $siz, $at, $mtime1) = stat($name2);

      if ($mtime1 > $mtime && !(-d $name2)) {
        $mtime = $mtime1;
      }

      next if $subcount == 0;

      #
      # Recurse into next lower subdirectory
      #

      $namedirtry = "/$startdir/";
      $namedirtry .= $name;

      ($dev, $ino, $mode, $nlink) = lstat($namedirtry);

      #next unless -d _;
      next unless { $nlink > 1 }
      &directory($name, *mtime, $nlink);

      --$subcount;
    }
  }
}