####################################################
# by wiebe @ QuakeNet
#
# a simple !kick script without chase:
#
#     [11:10:01] -!- nick1 is now known as nick2
#     [11:10:20] <@op> !kick nick1
#     [11:10:22] <@bot> nick1 not on channel
#     [11:10:45] <@op> !kick nick2
#     [11:10:46] nick2 was kicked from #chan by bot [requested]
#
# same thing, now with chase:
#
#     [11:10:01] -!- nick1 is now known as nick2
#     [11:10:20] <@op> !kick nick1
#     [11:10:21] nick2 was kicked from #chan by bot [requested]
#
####################################################

# use in ban kick warn queue voice devoice deop (not op?)

####################################################
# chase:nick
####################################################
bind nick -|- * chase:nick
proc chase:nick { n u h c m } {
  if {[isbotnick $n]} { return 0 }
  if {[string equal $c "*"]} { return 0 }
  set n [string tolower $n]; set m [string tolower $m]
  if {[string equal $n $m]} { return 0 }
  global chasedb; set t [clock seconds]; set u [md5 $u]; set chasedb($n) [split "$t $m $u"]
}


####################################################
# chase
####################################################
proc chase { n } {
  if {[string equal $n ""]} { return "" }
  global chasedb
  set n [string tolower $n]
  if {![info exists chasedb($n)]} { return "" }
  set s [clock seconds]; set t [lindex $chasedb($n) 0]
  if {[expr $s - $t] > "60"} { unset chasedb($n); return "" }
  set m [lindex $chasedb($n) 2]; set n [lindex $chasedb($n) 1]; set c 0
  while {[info exists chasedb($n)] && ![onchan $n]} {
# safety check, 8 nick changes in 60s in unrealistic, may be stuck in endless loop
    incr c 1; if {$c > "8"} { return "" }
    set t [lindex $chasedb($n) 0]
    if {[expr $s - $t] > "60"} { unset chasedb($n); return "" }
    set m [lindex $chasedb($n) 2]; set n [lindex $chasedb($n) 1]
  }
  if {[string equal [md5 [getchanhost $n]] $m]} { return $n }
  return ""
}


####################################################
# chase:time
####################################################
bind time -|- "* * * * *" chase:time
proc chase:time { mi ho da mo ye } {
  global chasedb; set n [clock seconds]
  foreach e [array names chasedb] {
    if {[expr $n - [lindex $chasedb($e) 0]] > "60"} { unset chasedb($e) }
  }
}


set scriptdb(chase) {
  "provides nick chasing, used in various other scripts, like for example kicking or banning etc. it works by keeping track of nick changes, when a script requests the current nick of a user, this script attempts to chase down the current nick"
}

