User:GreenC/awb/cygwin/demon-win

#!/bin/awk -f

@load "filefuncs"

BEGIN {

 # Begin configurations

  rm = "/usr/bin/rm"                # Path to Cygwin rm 
  sleep = "/usr/bin/sleep"          # Path to Cygwin sleep

  dir = "/cygdrive/h/"              # Shared directory with VirtualBox. RAM disk recommended.
  fname = dir "name.txt"            # File containing name passed *from* AWB
  farticle = dir "article.txt"      # File containing article passed *to* AWB
  fabort = dir "abort.txt"          # File flagging an abort from remote script

 # End configuration

  name = ARGV[1]

                                    # Clear any old files 
  removefile(farticle)
  removefile(fname)
  removefile(fabort)

  if(length(name) == 0)             # Abort if bad name data
    exit

  print name > fname
  close(fname)                      # Flush buffer

  print("demon-win.awk: Waiting for " farticle " ...")

  while(1) {
    sleep(1)
    if( exists(fabort) ) { 
      print("demon-win.awk: Received abort.txt")
      removefile(fabort)
      exit
    }
    if( exists(farticle) ) {
      print("demon-win.awk: Received article.txt")
      exit
    }
  }
}

# Delete a file
function removefile(str) {

      if( exists(str) )
        sys2var(rm " -- " str)
      if( exists(str) ) {
        print("demon-lin.awk: Unable to delete " str ", aborting.")
        exit
      }
      system("") # Flush insurance
}

#
# Check for file existence. Return 1 if exists, 0 otherwise.
#  Requires GNU Awk:
#     @load "filefuncs"
#
function exists(name    ,fd) {
    if ( stat(name, fd) == -1)
      return 0
    else
      return 1
}

#
# Run a system command and store result in a variable
#   eg. googlepage = sys2var("wget -q -O- http://google.com")
# Supports pipes inside command string. Stderr is sent to null.
# If command fails (errno) return null
#
function sys2var(command        ,fish, scale, ship) {

         command = command " 2>/dev/null"
         while ( (command | getline fish) > 0 ) {
             if ( ++scale == 1 )
                 ship = fish
             else
                 ship = ship "\n" fish
         }
         close(command)
         return ship
}

#
# Sleep
#
function sleep(seconds)
{
  sys2var(sleep " " seconds)
}