/*******************************************************************************
* Program name: remote_macros.sas
*
* Purpose:      Single file containing the macros necessary for remote
*               submission of jobs, via SAS/GRID or locally
* Credits:      This code is a slightly modified version of the code developed by
*               Duke University Department of Population Health Sciences
*               [B Hammill, S Lippmann, M Stagner]
*
*******************************************************************************/

/* Pauses the program for specified number of seconds */
%macro sleep(seconds);
    %let rc = %sysfunc(sleep(&seconds, 1));
%mend;

/* Initializes connections to remote parallel sessions */
%macro signon;

    * Ensure grid is enabled, if available;
    %if %upcase(&sasgrid.) = Y %then %do;
        %put gs_rc=%sysfunc(grdsvc_enable(_all_, server=&gridsrv.));
    %end;

    * Initialize session variables;
    %do s = 1 %to &numSession.;
        %global mySignonVar&s.;
        %global myRsubmitVar&s.;
        %let mySignonVar&s. = 3;
        %let myRsubmitVar&s. = 0;
    %end;

    * Sign onto remote CPUs;
    %do s = 1 %to &numSession.;
        SIGNON mySess&s. SIGNONWAIT=N CMACVAR=mySignonVar&s.
            %if %upcase(&sasgrid.) = N %then 
                sascmd="&sascmd."
            ;
        ;
    %end;

    * Wait 10 seconds for all sign-ons to complete;
    %sleep(10)

%mend;

/* Closes connections to remote parallel sessions */
%macro signoff;

    * Wait for all remote sessions to complete;
    WAITFOR _all_
        %do s = 1 %to &numSession.;
            mySess&s.
        %end;
    ;

    * Get remote log and listing files;
     %do s = 1 %to &numSession.;
%put ========================================= ;
%put log file for session &s ;
%put vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv ;
         rget mySess&s.;
%put ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ;
%put log file for session &s ;
%put ========================================= ;
     %end;    

    * Signoff;
    SIGNOFF _all_;

%mend;

* Wait for an available remote session and return number of open session when found;
%macro waitForAvailableSession;

    %global openSessID;
    %let sessFound = 0;
    
    %do %while (&sessFound. eq 0);
        %do s = 1 %to &numSession.;
            %if (&&mySignonVar&s. eq 0) %then %do;
                %if (&&myRsubmitVar&s. eq 0) %then %do;
                    %let openSessID = &s.;
                    %let sessFound = 1;
                    %let sess = &numSession.;
                    %put &=openSessID;
                %end;
            %end;
        %end;

        %if (&sessFound. eq 0) %then
            %sleep(5)
        ;
    %end;
%mend;