#!/usr/bin/env ruby
require 'yaml'
#
# the dir being watched
#
  dirwatch_dir = ENV['DIRWATCH_DIR']
#
# load entries from stdin.  this is a yaml doccument.
#
  entries = YAML::load STDIN
#
# process each entry
#
  entries.each do |entry| 
    #
    # get the path and mtime of the updated file
    #
      path, mtime = entry['path'], entry['mtime']
    #
    # split into directory and filename components
    #
      dirname, basename = File::split path 
    #
    # get the last directory component
    #
      dir = File::basename dirname
    #
    # perform actions based on dir - files contain numbers:
    #
    # - new files in dir 'a' get doubled and the result written to dir 'b'
    # - new files in dir 'b' get two added and the result written to dir 'c'
    # - new files in in dir 'c' are displayed as the result 
    #
    case dir
      when 'a'
        n = Integer(IO::read(path))
        n *= 2
        output = File::join dirwatch_dir, 'b', basename
        open(output, 'w'){|f| f.write n}
      when 'b'
        n = Integer(IO::read(path))
        n += 2
        output = File::join dirwatch_dir, 'c', basename
        open(output, 'w'){|f| f.write n}
      when 'c'
        n = Integer(IO::read(path))
        puts "result <#{ basename }> => <#{ n }>"
    end
  end
