#!/bin/env ruby


require "filelock"; include FileLock


def test1
   STDOUT.sync = true
   file = "tt.t"
   print "File is '%s'\n" % file
   print "Look for the smileys; they indicate test state:\n\n"
   print "   :-)  -- means test successful\n"
   print "   :-(  -- means test failed\n\n"
   begin
      print "Try to lock fp1 ... "
      fp1 = LockedFile.open(file, "w")
      print "success! :-)\n"
   rescue AcquireLockError
      print "failed! :-(\n"
   end
   begin
      print "Try to lock fp2 (DON'T STEAL) ... "
      fp2 = LockedFile.new(file, 8, 2, 2)
      print "success! :-(\n"
   rescue AcquireLockError
      print "failed! :-)\n"
   end
   begin
      print "Try to lock fp3 (STEAL IT) ... "
      fp3 = LockedFile.new(file, "w", 8, nil, 2, 1)
      print "success! :-)\n"
   rescue AcquireLockError
      print "failed! :-(\n"
   end
   begin
      print "Try to write into fp1 ... "
      fp1.write("Hello World\n")
      print "success?!? :-( But lock was stolen (Ooops!!!)?!?\n"
   rescue StolenLockError
      print "failed! :-) Lock stolen (I am sooooo sorry)\n"
   end
   begin
      print "Try to write into fp3 ... "
      fp3.write("Hello World\n")
      print "success! :-) With stolen lock (whistles in the night)!\n"
   rescue StolenLockError
      print "failed?!? :-( Lock stolen (huh! Who? When? How?)?!?\n"
   end
   begin
      print "Try to close fp1 ... "
      fp1.close
      print "success?!? :-( Although lock was stolen (erhm ...)?!?\n"
   rescue StolenLockError
      print "failed! :-) Lock stolen (Who did such things?)\n"
   rescue UnlockError
      print "failed?!? No lock (Oops)?!?\n"
   end
   begin
      print "Try to close fp3 ... "
      fp3.close
      print "success! :-) With stolen lock (har, har, har)!\n"
   rescue StolenLockError
      print "failed! :-( Stolen lock (What??? catch the thiefe)?!?\n"
   rescue UnlockError
      print "failed! :-( No lock (What is happend now????)?!?\n"
   end
   File.unlink file
end

def test2(file)
   require "mailread"

   if File.exist?(file)
      atime = File.atime(file)
      mtime = File.mtime(file)
      f = LockedFile.new(file)
      begin
         until f.eof?
            mail = Mail.new(f)
            print mail.header['Date'][0..19], " "
            print mail.header['From'][0..19], " "
            print "'%s'\n" % mail.header['Subject'][0..35]
         end
      ensure
         f.close
         File.utime(atime, mtime, file)
      end
   end
end

test1
