#! /usr/bin/tclsh7.6

set filterdir [lindex $argv 0]
set level [lindex $argv 1]
set logfile [lindex $argv 2]
set letterId [lindex $argv 3]

##################################################
### now check to see if we can extract an
### email address
##################################################
set user [join [lrange $argv 4 end] " "]
set email ""
# blackie@imada.sdu.dk (Jesper Pedersen)
if {![regexp {^ *([^@]*@[^ ]*) *\(.*\) *$} $user all email]} {
  # Jesper Pedersen <blackie@imada.sdu.dk>
  if {![regexp {.*<([^@]*@[^ >]*)> *$} $user all email]} {
    # blackie@imada.sdu.dk
    regexp {^ *([^@ ]*@[^ ]*) *$} $user all email
  }
}

if {$logfile != ""} {
  set LOG [open $logfile a]
}

if {$email == "" && ($level & 8)} {
  puts $LOG "$letterId: Email address could not be extracted\n"
}

if {$email != "" && ![file exists $filterdir/$email] && ($level & 2)} {
  puts $LOG "$letterId: No signature file found for email address \"$email\"\n"
}

if {$email == "" || ![file exists $filterdir/$email]} {
  gets stdin line
  while {![eof stdin]} {
    puts $line
    gets stdin line
  }
  exit 0
}

##################################################
### Read in the signature for the given user
##################################################
set FILE [open $filterdir/$email]
set max 0
gets $FILE line
while {![eof $FILE]} {
  set sig$max $line
  incr max
  gets $FILE line
}
close $FILE

##################################################
### now read from standard input
##################################################
gets stdin line
set current 0
set sigrem 0
while {![eof stdin]} {
  if {$current == [expr $max-1]} {
    set current 0
    set sigrem 1
    puts "<signature removed>"
  } else {
    if {![string compare [set sig$current] $line]} {
      set buf$current $line
      incr current
    } else {
      if {$current != 0} {
        for {set i 0} {$i < $current} {incr i} {
          puts [set buf$i]
        }
        set current 0
      }
      puts $line
    }
  }
  gets stdin line
}

if {$sigrem && ($level & 1)} {
  puts $LOG "$letterId: removed signature for letter from \"$email\"\n"
}
if {!$sigrem && ($level & 4)} {
  puts $LOG "$letterId: Signature not matched for letter from \"$email\"\n"
}

close $LOG
