/*************************************************

   sysmessage.rexx

   Author: Jeremy Friesner (jaf@chem.ucsd.edu)
   
   An ARexx script that sends a system message to
   all clients logged in to the local AMarqueed
   server.

   Usage:  rx sysmessage.rexx hostnames lognames message
   
   (hostnames) should be a regular expression denoting
   the hostnames of the client or clients to be messaged.
   (e.g. sdcc8.ucsd.edu or #?.edu)
   
   (lognames) should be a regular expression denoting
   the lognames of the AMarquee client or clients to
   be messaged (e.g. #?Netris or QAmiTrack).
   
   (message) Should be the message you want to send.
   
   Example:  rx sysmessage.rexx #? #? The system is shutting down!

   Note that you must have given localhost 
   AMARQUEED_SENDSYSMESSAGE privilege in order for
   this script to work.

***************************************************/

parse arg hostnames lognames message 

if ((serverName == '?')|(length(hostnames) = 0)|(length(lognames)=0)) then do
  say "Usage: rx sysmessage.rexx <hostnames> <logNames> <message>"
  exit
  end
  
serverName   = 'localhost'  /* hardcoded for now */
portNum = 2957
logName = 'sysmessage.rexx'

if (length(lognames) = 0) then lognames = '#?'
if (length(message) = 0) then message = 'This is a system message.'

message = strip(message) /* Remove extra spaces */

/* We need to trap all the different ways the script could exit,
   so that we can be sure any allocated QSessions or QMessages are
   freed properly */
signal on error
signal on syntax
signal on halt
signal on break_c

/* Used to track allocated QSession */
session = 0

/* Note the offset MUST be -204, and not -30 like in many other
   libraries!  Note also that we require amarquee.library v46 or higher */
check = addlib('amarquee.library', 0, -204, 46)

say "Connecting to server " || serverName || " on port " || portNum || " as " || logName
session = QNewSession(serverName, portNum, logName)
if (session > 0) then 
do
  messagereceivers = "/" || hostnames || "/" || lognames
  say "Sending System Message to: " || messagereceivers
  
  call QRequestPrivilegesOp(session, QPRIV_SENDSYSMESSAGES)  

  /* Note that this won't work if the server doesn't give us
     the privilege; this script doesn't check to see if the
     privilege was actually granted, but rather assumes that it
     was. */
  call QSysMessageOp(session,messagereceivers,message)
  
  /* And off it goes... */
  call QGo(session)
end

/* Our error handling/cleanup routine starts here */
ERROR:
SYNTAX:
HALT:
BREAK_C:
  say "Cleaning up..."
  if (session > 0) then do
    call QFreeSession(session)
    end
  exit
