#  Copyright (c) 2018
#  Charles Jordan (Hokkaido University, Sapporo, Japan),
#  Michael Joswig, Lars Kastner (Technische Universitaet Berlin, Germany)
# 
#  This program is free software; you can redistribute it and/or modify it
#  under the terms of the GNU General Public License as published by the
#  Free Software Foundation; either version 3, or (at your option) any
#  later version: http://www.gnu.org/licenses/gpl.txt.
# 
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#-------------------------------------------------------------------------------

#!/usr/bin/env perl
use strict;
use warnings;
use File::Basename;

my $prefix = $ARGV[0];
my $versionFilePath = "$prefix/lib-src-ReverseSearch/version.hh";
my $mptopcomVersion = "1.1";

my $full_version = get_version_string($prefix, $mptopcomVersion);

if(-e "$versionFilePath") {
   my $oldVersion = `cat $versionFilePath | grep MPTOPCOM_VERSION_STRING`;
   ($oldVersion) = $oldVersion =~ m/"(version.*)"/;
   if($oldVersion ne $full_version){
      `rm $versionFilePath`;
      write_version_file($versionFilePath, $full_version);
   }
} else {
   write_version_file($versionFilePath, $full_version);
}



sub get_version_string {
   my($prefix, $version) = @_;
   my $result = "version $version";
   if(-d "$prefix/.git") {
      my $branch = `cd $prefix; git rev-parse --abbrev-ref HEAD`;
      chomp $branch;
      $result .= ", branch $branch ";
      my $commit = `cd $prefix; git rev-parse HEAD`;
      chomp $commit;
      $commit = substr($commit, 0, 10);
      my $upstream = `cd $prefix; git rev-parse --abbrev-ref --symbolic-full-name \@{u} 2>&1`;
      if($upstream =~ m/fatal: no upstream configured for branch/){
         return $result."[commit $commit]";
      }
      chomp $upstream;
      unless ($?) {
         my ($ahead,$behind) = split '\t',`cd $prefix; git rev-list --left-right --count $branch...$upstream`;
         chomp $ahead;
         chomp $behind;
         $result .= "[";
         $result .= "$ahead ahead " if ($ahead > 0);
         $result .= "$behind behind " if ($behind > 0);
         $result .= "$upstream, commit $commit]";
      }
   } 
   return $result;
}



sub write_version_file {
   my($filename, $versionString) = @_;
   open(my $file, ">$filename") or die "Could not open $filename.";
   print $file <<"---";
#ifndef MPTOPCOM_VERSION_HH
#define MPTOPCOM_VERSION_HH
#define MPTOPCOM_VERSION_STRING "$versionString"
#endif
---
   close($file);
}

