/**
  @file
  @brief Register a new licence key
  @details

  <h4> SAS Macros </h4>
  @li mpeinit.sas
  @li bitemporal_dataloader.sas
  @li mp_abort.sas
  @li mf_getuser.sas
  @li mpe_getgroups.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.

  @test

      echo '{"keyupload":[{"activation_key":"slfdjasfda;dslf","licence_key":"asdfasdlfkajsfdas"}]}'>in.json
      sasjs request admin/registerkey -d in.json

**/

%mpeinit()

/* determine users group membership */
%mpe_getgroups(user=%mf_getuser(),outds=work.groups)
%global admin_check;
proc sql;
select count(*) into: admin_check
  from groups where groupname="&mpeadmins";

%mp_abort(iftrue= (&admin_check = 0)
  ,mac=%str(&_program)
  ,msg=%str(Only members of &mpeadmins may register a key)
)

%global licencekey activation_key;
data _null_;
  set work.keyupload;
  call symputx('activation_key',activation_key);
  call symputx('licencekey',licence_key);
  call symputx('activlen',length(activation_key));
  call symputx('liclen',length(licence_key));
run;

%mp_abort(iftrue= (&activlen< 10)
  ,mac=%str(&_program)
  ,msg=%str(Invalid activation_key)
)
%mp_abort(iftrue= (&liclen < 10)
  ,mac=%str(&_program)
  ,msg=%str(Invalid licencekey)
)

data work.loadme;
  if 0 then set &mpelib..mpe_config;
  VAR_SCOPE='DC';
  VAR_NAME='DC_ACTIVATION_KEY';
  VAR_VALUE=symget('activation_key');
  VAR_ACTIVE=1;
  output;
  VAR_NAME='DC_LICENCE_KEY';
  VAR_VALUE=symget('licencekey');
  VAR_ACTIVE=1;
  output;
  keep VAR_: ;
run;

%bitemporal_dataloader(
    tech_from=tx_from
    ,tech_to = tx_to
    ,base_lib=&mpelib
    ,base_dsn=mpe_config
    ,append_lib=WORK
    ,append_dsn=loadme
    ,PK= VAR_SCOPE VAR_NAME
    ,ETLSOURCE=%str(&_program STP)
    ,LOADTYPE=TXTEMPORAL
    ,dclib=&mpelib
)

data work.return;
  msg='SUCCESS';
run;

%webout(OPEN)
%webout(OBJ,return)
%webout(CLOSE)
