#!/usr/bin/perl

#
# build obo file if needed
#

use strict;
use Time::Local;

use constant FLAT2OBO => "/share/go/bin/oboedit/current/flat2obo";
use constant LOGFILE => "/share/go/logs/build_obo.log";

my %files = (FUNC => "/share/ftp/pub/go/ontology/function.ontology",
	     COMP => "/share/ftp/pub/go/ontology/component.ontology",
	     PROC => "/share/ftp/pub/go/ontology/process.ontology",
	     DEF  => "/share/ftp/pub/go/ontology/GO.defs",
	     OBO  => "/share/ftp/pub/go/ontology/gene_ontology_edit.obo",
	     );

my %filetimes = ();

open (LOG, ">>" . LOGFILE) || die "Cannot open log file, " . LOGFILE . "\n";

#
# select LOGFILE so that flat2obo and cvs output is captured
#
select (LOG); $| = 1;

print "---------------\n";
print scalar localtime, "\n";
print "---------------\n\n";

foreach my $file (keys %files) {
    #  index to the array from stat() in next line:
    #  $dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks
    #
    #  we'll use the "last modify time" of the file, index 9
    #
    my ( @stats ) = stat $files{$file};

    $filetimes{$file} = @stats[9];
}

my $obotime = timelocal(localtime($filetimes{'OBO'}));

my $rebuild = 0;

foreach my $file (keys %files) {
    if ($file ne "OBO") {
	my $filetime = timelocal(localtime($filetimes{$file}));

	if ($filetime == 0) {
	    die "Required file, $files{$file}, is missing!\n";
	}

	if ($filetime > $obotime) {
	    print "NEWER\t$files{$file} than OBO\n";
	    $rebuild = 1;
	} else {
	    print "OLDER\t$files{$file} than OBO\n";
	}
    }
}

#
# if OBO file is older than any of the three ontology files or the definition file
# the OBO file needs to be rebuilt.
#

if ($rebuild) {
    print "\nRebuild of " . $files{OBO} . " file starting.\n";

    my $dstr = `date +%Y%m%d`;
    chomp $dstr;

    # clone LOG filehandler to STDERR
    open (STDOUT, ">&LOG") || die "Cannot dup LOG filehander for STDOUT: $!\n";
    open (STDERR, ">&LOG") || die "Cannot dup LOG filehander for STDERR: $!\n";

    # rebuild obo file
    my $cmd = FLAT2OBO . " --gopresets $files{FUNC} $files{COMP} $files{PROC} -def $files{DEF} -o $files{OBO}";

    my $status = system($cmd);

    if ($status) { die "FATAL: flat2obo execution failed: $!\n"; }

    # commit updated obo file
    my $cmd = "/usr/bin/csh -c 'unlimit; /tools/gnu/bin/cvs -d /share/go/cvs commit -m $dstr $files{OBO}'";

    my $status = system($cmd);

    if ($status) { die "FATAL: cvs commit failed: $!\n"; }

} else {
    print "OBO file is up-to-date, " . $files{OBO} . "\n";
}

print "\n";

close LOG;

exit 0;

