#!/usr/bin/perl

#
# build obo file if needed
#

use strict;
use Time::Local;

use constant OBO2OBO => "/share/go/bin/oboedit/current/obo2obo";
use constant LOGFILE => "/share/go/logs/build_obo2obo.log";

# OBO10 is the output, the OBO v1.0 file
# OBO12 is the input, the OBO v1.2 file

my %files = (
	     OBO10  => "/share/ftp/pub/go/ontology/gene_ontology.obo",
	     OBO12  => "/share/ftp/pub/go/ontology/gene_ontology_edit.obo",
	     STRIPSCRIPT => "/share/go/bin/oboedit/current/docs/examplescripts/strip_disjoint_and_replaced_by_tags.osl",
	     );

my %filetimes = ();

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

#
# select LOGFILE so that obo2obo 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 $oboedittime = timelocal(localtime($filetimes{'OBO12'}));

my $rebuild = 0;

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

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

	if ($filetime < $oboedittime) {
	    print "OLDER $files{$file} than OBO v1.2\n";
	    $rebuild = 1;
	} else {
	    print "NEWER $files{$file} than OBO v1.2\n";
	}
    }
}

#
# if OBO v1.2 file is newer than the OBO v1.0 file, the OBO v1.0 file needs to be rebuilt
#

if ($rebuild) {
    print "Rebuild of " . $files{OBO10} . " 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 = OBO2OBO . " -formatversion OBO_1_0 $files{OBO12} -o $files{OBO10}";

    my $cmd = OBO2OBO . " -formatversion OBO_1_0 $files{OBO12} -writecomments -o $files{OBO10} -runscript $files{STRIPSCRIPT} \\\;";

    my $status = system($cmd);

    if ($status) { die "FATAL: obo2obo 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{OBO10}'";
    my $status = system($cmd);

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

} else {
    print "no update is needed for OBO v1.0 file, " . $files{OBO10} . "\n";
}

print "\n";

close LOG;

exit 0;

