#!/usr/bin/tclsh
package require inotify
package provide tailf

namespace eval tailf {
namespace export fadd frem

array set File {}

inotify create ::tailf::watch ::tailf::handler

proc getpos {filepath} {
    set fd [open $filepath r]
    seek $fd 0 end
    set pos [tell $fd]
    close $fd
    return $pos
}

proc handler {fd} {
    variable File
    set events [watch read]
    puts $events
    foreach {watchId flags cookie filepath} $events {
        puts "|$watchId| |$flags| |$cookie| |$filepath|"
        #if {"w" in $flags} { continue }
        set diff {}
        set old [lindex $File($filepath) 0]
        puts "old: $old"
        set new [getpos $filepath]
        puts "new: $new"

        if {$old != $new} {
            set fd [open $filepath r]
            seek $fd 0 $old
            fconfigure $fd -blocking no -buffering line
            puts B
            while {[gets $fd line] > 0} {
                puts A
                lappend diff $line
            }
            close $fd
        }

        set File($filepath) [list $new $callback]
        eval [list $callback $filepath $diff]
        puts OK
    }
    puts EXIT
    return
}

proc fadd {filepath callback} {
    set pos [getpos $filepath]
    set File($filepath) [list $pos $callback]
    watch add $filepath {w}
}

proc frem {filepath} {
    unset File($filepath)
    watch del $filepath
}

} ;# namespace

proc proc132 {filepath diff} {
    puts $diff
}

::tailf::fadd {132.txt} proc132

set a {}
vwait a
