/*
   Example of using the RXMMP library.

   The example demonstrates the use of low-level functions mmpSendCmd() and
   mmpRead() to work with the protocol to obtain a list of all domains and
   users.
*/

parse arg MMPServer MMPUser MMPPassword

if MMPPassword = "" then
do
  parse source srcOS " " srcMode " " srcFile
  srcFile = filespec( "name", srcFile )
  say "Usage: " || srcFile || " server:port username password"
  exit
end

if RxFuncQuery("mmpLoadFuncs") then
do
  call RxFuncAdd "mmpLoadFuncs", "RXMMP", "mmpLoadFuncs"
  call mmpLoadFuncs
end

/* Connect to the MMP server and log in. */

MMPHandle = mmpCreate( MMPServer, MMPUser, MMPPassword )
parse var MMPHandle resStatus ":" resError
if resStatus = "ERROR" then
  call die "mmpCreate", resStatus, resError

say "User level: " || mmpQueryUserLevel( MMPHandle )
say "Username: " || mmpQueryUsername( MMPHandle )


/* Query domain list */

parse value mmpSendCmd( MMPHandle, "LIST DOMAINS" ) with resStatus ":" resError
if resStatus \= "SUCCESS" then
  call die "mmpSendCmd", resStatus, resError

/* Receive domain names */

count = 0
do forever
  parse value mmpRead( MMPHandle, "reply" ) with resStatus ":" resError
  if resStatus \= "SUCCESS" then
    call die "mmpRead", resStatus, resError

  /* First item - reply type: * / OK / NO / BYE */
  if reply.1 \= "*" then
  do
    if reply.1 \= "OK" then
      say "Reply type: " || reply.1
    leave
  end

  count = count + 1
  domains.count = reply.2
end
domains.0 = count

/* Output domains */

do i = 1 to domains.0
  say "Domain: " || domains.i

  cmd = "LIST USERS:" || domains.i
  parse value mmpSendCmd( MMPHandle, cmd ) with resStatus ":" resError
  if resStatus \= "SUCCESS" then
    call die "mmpSendCmd", resStatus, resError

  do forever
    parse value mmpRead( MMPHandle, "reply" ) with resStatus ":" resError
    if resStatus \= "SUCCESS" then
      call die "mmpRead", resStatus, resError

    /* First item - reply type: * / OK / NO / BYE */
    if reply.1 \= "*" then
    do
      if reply.1 \= "OK" then
        say "Reply type: " || reply.1 || ", " || reply.2
      leave
    end

    say "  " || reply.2 || " (used: " || reply.4 || "/" || reply.3 ||,
        ", flags: """ || reply.5 || """)"
  end
end


/* Log out, close the connection and destroy the MMP Client object. */
call mmpDestroy( MMPHandle )

call mmpDropFuncs

exit


/* DIE func.name, result status, error text */
die:
  say arg(1) || "(): " || arg(2) || " (" || arg(3) || ")"
  call mmpDropFuncs
  exit
