/**
  @file getauditfile.sas
  @brief Downloads a zip file containing audit info.
  @details  The staging location from the &mpelocapprovals location
    is zipped and returned as a file download.  A user can only request the
    audit pack if they have EDIT or APPROVE rights on the target table.

  <h4> SAS Macros </h4>
  @li mf_getuser.sas
  @li mf_verifymacvars.sas
  @li mpe_accesscheck.sas
  @li mp_abort.sas
  @li mp_dirlist.sas
  @li mp_binarycopy.sas
  @li mf_getattrn.sas
  @li mp_streamfile.sas


  @version 9.2
  @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.

**/

%mpeinit()
options mprint;

/* security checks */
%let user=%mf_getuser();

proc sql noprint;
select cats(base_lib,'.',base_ds) into: libds
  from &mpelib..mpe_submit
  where table_id="&table";

%mp_abort(
  iftrue=(%mf_verifymacvars(libds table)=0)
  ,mac=&_program
  ,msg=%str(Missing: libds table)
)

%mpe_accesscheck(&libds,outds=authEDIT,user=&user,access_level=EDIT);
%mpe_accesscheck(&libds,outds=authAPP,user=&user,access_level=APPROVE);

%mp_abort(
  iftrue=(
    %mf_getattrn(work.authEDIT,NLOBS)=0 & %mf_getattrn(work.authAPP,NLOBS)=0
  )
  ,mac=mpestp_audit
  ,msg=%str(&user not authorised to download audit data for &table)
)

ods package(ProdOutput) open nopf;

options notes source2 mprint;
%let table=%unquote(&table);
%mp_dirlist(outds=dirs, path=&mpelocapprovals/&TABLE);
data _null_;
  set dirs;
  retain str1
    "ods package(ProdOutput) add file='&mpelocapprovals/&TABLE/";
  retain str2 "' mimetype='text/plain' path='contents/';";
  call execute(cats(str1,filename,str2));
run;

%let archive_path=%sysfunc(pathname(work));

ods package(ProdOutput) publish archive  properties
      (archive_name=  "&table..zip" archive_path="&archive_path");

ods package(ProdOutput) close;

%mp_abort(iftrue= (&syscc ne 0)
  ,mac=&_program..sas
  ,msg=%nrstr(syscc=&syscc)
)

/* now serve zip file to client */
%mp_streamfile(contenttype=ZIP
  ,inloc=%str(&archive_path/&table..zip)
  ,outname=&table..zip
)

%mpeterm()
