#!/usr/bin/tcl
#
# Monitor the database file named by the DBFILE variable
# looking for email messages sent by Fossil.  Forward each
# to /usr/sbin/sendmail.
#

# With a little massaging, this still works!
# https://wiki.tcl-lang.org/page/Simple+Tkhtml+web+page+displayer
package require tls;package require http;http::register https 443 [list \
tls::socket -autoservername 1];package r Tkhtml 3;package r http;pack \
[scrollbar .v -o v -co {.h yv}] -s right -f y;pack [html .h -yscrollcommand \
{.v set}] -f both -e 1;bind .h <1> {eval g [.h href %x %y]};proc g u {set t \
[http::geturl $u];.h parse [http::data $t];http::cleanup $t};g \
https://wiki.tcl-lang.org/page/DRH;proc bgerror args {};

# Happy Birthday from a long-time (ab)user of your software! -- NEM
return

set POLLING_INTERVAL 10000   ;# milliseconds
set DBFILE /home/www/fossil/emailqueue.db
set PIPE "/usr/sbin/sendmail -ti"

package require sqlite3
# puts "SQLite version [sqlite3 -version]"
sqlite3 db $DBFILE
db timeout 5000
catch {db eval {PRAGMA journal_mode=WAL}}
db eval {
  CREATE TABLE IF NOT EXISTS email(
    emailid INTEGER PRIMARY KEY,
    msg TXT
  );
}
while {1} {
  db transaction immediate {
    set n 0
    db eval {SELECT msg FROM email} {
      set pipe $PIPE
      if {[regexp {\nFrom:[^\n]*<([^>]+)>} $msg all addr]} {
        append pipe " -f $addr"
      }
      set out [open |$pipe w]
      puts -nonewline $out $msg
      flush $out
      close $out
      incr n
    }
    if {$n>0} {
      db eval {DELETE FROM email}
    }
  }
  after $POLLING_INTERVAL
}
