#
# Usage:
#
# mpms wait [<timeout> [<interval>]]
#
#   wait for mpms script and return file content
#   timeout is a week by default, interval 1 second
#
#   set text [mpms wait]
#
#   alternative usage (polling):
# 
#   while {[mpms wait 1] ne ""} {
#     DO SOMETHING
#   }
#   set text [mpms wait]
#
# mpms continue
#
#   continue mpms script (deleting the file)
#

proc mpms {command {timeout 600000} {interval 1}} {
  global env

  set path $env(HOME)/MPMS/ReqToExt.txt
  switch -- $command {
    wait {
      set start [DoubleTime]
      while 1 {
        if {[file exists $path]} {
          set fil [open $path r]
          set contents [read -nonewline $fil]
          close $fil
          return $contents
        }
        if {[DoubleTime] >= $start + $timeout} {
          return ""
        }
        wait $interval
      }
    }
    continue {
      if {[file exists $path]} {
        file delete $path
        return 1
      }
      return 0
    }
    default {
      error "what is $command ?"
    }
  }
}

publishLazy mpms
