/**
  @file dc_assignlib.sas
  @brief Assigns macros
  @details There are two versions of this macro - a META and a VIYA version (in
  different folders).  The interfaces is the same.  This version is META.

  <h4> SAS Macros </h4>
  @li mm_assignlib.sas
  @li mm_assigndirectlib.sas
  @li mm_getrepos.sas

  @version 9.3
  @author 4GL Apps Ltd
  @copyright 4GL Apps Ltd.  This code may only be used within Data Controller
    and may not be re-distributed or re-sold without the express permission of
    4GL Apps Ltd.
**/

%macro dc_assignlib(type,libref,passthru=);
%put &sysmacroname entry vars:;
%put _local_;

/* take current repository */
%local repo repocnt x;
%let repo=%sysfunc(getoption(metarepository));

/* get list of repositories and filter */
%mm_getrepos(outds=repos)
%let repocnt=0;
data repos;
  set repos;
  where repositorytype in('CUSTOM','FOUNDATION')
    & upcase(name) ne "%upcase(&repo)";
  keep id name ;
  call symputx(cats('repo',_n_),name,'l');
  call symputx('repocnt',_n_,'l');
run;

/* find out which of these repositories has the libref we are searching for */
%local lib_uri;
%let lib_uri=NOTFOUND;
data _null_; /* check default repo first */
  length lib_uri $256;
  call missing (of _all_);
  rc=metadata_getnobj("omsobj:SASLibrary?@Libref ='&libref'",1,lib_uri);
  call symputx('lib_uri',coalescec(lib_uri,'NOTFOUND'),'l');
run;
%if &lib_uri=NOTFOUND %then %do;
  %do x=1 %to &repocnt;
    options metarepository=&&repo&x;
    data _null_;
      length lib_uri $256;
      call missing (of _all_);
      rc=metadata_getnobj("omsobj:SASLibrary?@Libref ='&libref'",1,lib_uri);
      call symputx('lib_uri',coalescec(lib_uri,'NOTFOUND'),'l');
    run;
    %if &lib_uri ne NOTFOUND %then %let x=%eval(&repocnt+1);
  %end;
%end;


%if &type=READ %then %do;
  %mm_assignlib(&libref)
%end;
%else %if &type=WRITE %then %do;
  %mm_assigndirectlib(&libref,open_passthrough=&passthru)
%end;

options metarepository=&repo;

%mend dc_assignlib;
