% MEQVER Returns current version number for the MEQ toolbox.
%
% Now also returns information about commit, tag and url of meq and
% dependencies (genlib, psitbx).
%
% [+MEQ MatlabEQuilibrium Toolbox+] Swiss Plasma Center EPFL Lausanne 2022. All rights reserved.
function [v,code] = meqver()

v=0; % Init meq version number

% Get meq, genlib and psitbx
codepaths = {fileparts(mfilename('fullpath')),fileparts(which('greenem')),fileparts(which('psitbxtcv'))};
if nargout < 2, codepaths = codepaths(1);end % Only meq is needed for its version number
ncodes = numel(codepaths);
[code.commit,code.tag,code.url] = deal(cell(ncodes,1));
for ii = 1:ncodes
 codepath = codepaths{ii};
 [sha1,tag,url] = deal('');
 % Parse version info from SPC .this-deployment.info file
 deploy_info = fullfile(codepath,'.this-deployment.info');
 if exist(deploy_info,'file')
  fid = fopen(deploy_info);
  while(true)
   tline = fgetl(fid);
   if ~ischar(tline), break;end
   name = regexp(tline,'^([^:]*): (.*)','tokens');
   if isempty(name), continue;end
   switch name{1}{1}
     case 'GIT_COMMIT',         sha1 = name{1}{2};
     case 'GIT_TAG',            tag  = name{1}{2};
     case 'GITLAB_PROJECT_URL', url  = name{1}{2};
   end
  end
 % else from existing git dir
 elseif exist(fullfile(codepath,'.git'),'dir')
  gitcmd = ['git -C ',codepath];
  [~,sha1] = system([gitcmd,' rev-parse --short HEAD']);
  [~,tag ] = system([gitcmd,' describe --tag']);
  [~,url ] = system([gitcmd,' remote -v | grep fetch | cut -f 2 | cut -d " " -f 1']);
 end
 
 code.commit{ii}  = strtrim(sha1);
 code.tag{ii}     = strtrim(tag);
 code.url{ii}     = strtrim(url);
 
 tokens = regexp(strtrim(tag),'^crpptbx-release-v(\d+)\.(\d+)\.(\d+)$','tokens');
 
 if ~isempty(tokens)
  % recognised tag
  if ii == 1, v=str2double(tokens{1}{1})+str2double(tokens{1}{2})*0.01; end % Get meq version number (assumes minor version < 100)
  assert(str2double(tokens{1}{2})<100,'minor version number must be <100')
 end
end