##########################################################################
### Script:  GreetWondeR                                               ###
### Version: 1.0.3                                                     ###
### Required: Eggdrop 1.3.x                                            ###
### Author:  Wingman <Wingman@Defiant.vilstal.net>                     ###
##########################################################################

### FEATURES: (for a short guide, try .greethelp guide (DCC))
#   - full multi channel support
#   - each chan owner can set individual greets for his chan...
#   - supports flag greets
#   - can either msg/notice all users, just non-users or only known users
#   - greets can be turned off
#   - all settings can be changed via dcc
#   - simple floot protection (in case of flood joins, the tcl will shut
#     down itself and restart at a certain number of mins)
#   - supports var replacing, e.g. if u add a greet 
#     ".+greet Welcome (nick) to (chan) - For a help try /msg (botnick) help"
#     and let's say Wingman joins #Eggdrop, he'll see:
#     Welcome Wingman to #Eggdrop - For a help try /msg Eggie help
#     WARNING: There are only 3 vars, which are replaced: (nick), (chan) and
#     (botnick) and if there's a char in front of or at the end of these
#     words, it will NOT BE REPLACED (e.g. (nick)! or bla(chan)blubb)
#   - and many more... (try .greethelp for a commandlist)

##########################################################################
### SETTINGS                                                           ###
##########################################################################

### GENERAL (GLOBAL)

# These are standard settings, which can be changed individually for each 
# channel by dcc commands (try .greethelp) 

# [dir] In what dir should i save the data?
set greet(dir) "./greet"

# [file] Where sould i save the data?
set greet(data) "greet.dat"

# [file] Where sould i save the individual nick greets?
set greet(nicks) "nicks.dat"

# [lines] How many lines are allowed for greets?
set greet(max) 5

# [NOTICE/PRIVMSG] How should i greet the users?
set greet(how) "NOTICE"

# [0/1/2] Should i greet all (1), known users (0) or only unkown
# users (2)?
set greet(all) 1

### FLOOD PROTECTION SETTINGS (HIGHLY RECOMMEND TO ENABLE!)

# [0/1] Enables the simple flood protection for this tcl. This means,
# if there's a flood join, the tcl refuses the greets for n minutes
set greet(floodprotect) 1 

# [joins:secs] How many joins in how many secs for red alert? :)
set flood(time) 5:8

# [mins] How long should the tcl shutdown itself after a flood attack?
set greet(noresponse) 10

###########################################################################
### HISTORY/CHANGES                                                     ###
###########################################################################

### Version 1.0.0
#   - uhm, added a lot of stuff and fixed a lot of bugs ;)

### Version 1.0.1
#   Foundby   Fixedby   What...
#             Wingman   added .+/-greetnick <handle> (<how> <text>)
#   Cocko     Wingman   forgot a close $file at +greet, whick 'caused
#                       a tcl error: too many open files
#             Wingman   rewrote the init code for a better update of older
#                       versions
#             Wingman   modified .greetstatus
#  Cocko      Wingman   forgot a ) in proc greet:join *grmml*
#  Cocko      Wingman   he's really lazy... ;) modified -greet, now u don't
#                       need to enter the whole greet text, just the first
#                       words...
#             Wingman   added .greetnickview for a list of nick-greets
#  Wingman    Wingman   nick was not greeted, if a nick-greet was set...
#
#  Wingman    Wingman   f%#ck typo... unkown -> unknown, 'cause of this
#                       typo, it's hard to update without removing all
#                       greets...

### Version 1.0.2
#  Wingman    Wingman   greet(max) didn't work anymore after update to
#                       .+greet <flags>
#  Wingman    Wingman   again - rewriting of the init code 'cause of this
#                       lame typo (unkown -> unknown)...
#  Cocko      Wingman   and again...forgot a close $file in greet:join
#  Cocko      Wingman   global +o did`nt get the chan +o greet...
#  Wingman    Wingman   forgot check at .greetstatus, if file exists
#                       $greet(nicks)
#             Wingman   some minor bugfixings
#  Wingman    Wingman   forgot to remove a exec rm (part of the old code),
#                       which 'caused a tcl error, if u del all greets
#                       on #chan and tried a .greetview...
#             Wingman   moved .greetall -> greetwho <all/known/unknown>
#             Wingman   added .greetreset for a complete greet reset
#  Cocko      Wingman   argh, bug in getvar... (close $file ;))
#  Wingman    Wingman   .greethelp -> greetwho [channel] <0/1/2> should be
#                       greetwho [channel] <all/known/unknown>
#  Cocko      Wingman   forgot a global greet in the flood subroutines,
#                       which cause a tcl error and a seg fault :)
#  Wingman    Wingman   nick-greet -> matched $nick and not $handle
#             Wingman   tried to shorten the proc greet:join code...

### Version 1.0.3
#             Wingman   several smaller bugfixes
#             Wingman   moved name SimpleGreet -> GreetWondeR
#                       _Simple_ did'nt get it anymore ;)
#             Wingman   added GreetWondeR motd (can be turned off via .gmotd)
#             Wingman   modified .+greet, now all flags are allowed
#             Wingman   rewrote the init code 'cause of now supporting all
#                       flags...
#             Wingman   rewrote greetsaving (+/-greet) and greetstatus
#             Wingman   rewrote the greet code...
#                       Now there are no more file-readings on joins
#             Wingman   *grrrr* on first start of eggdrop, [channel] == "" 
#                       this suxx ->> let's write proc [channels] new :)
#                       (now [getchannels])
#             Wingman   Added a short introduction (.greethelp guide)

###########################################################################
###             CODE - please change anything below :)                  ###
###########################################################################

if {![info exists numversion] || ($numversion < 1030000)} {
  if {[string range $version 0 2] != "1.3"} {
    putlog "TCL: GreetWondeR $greet(version) - Error: at least Eggdrop v1.3.0 required"
    return 0
    }
  }

bind dcc n greetnickview dcc:greetnickview
bind dcc n greetreset dcc:greetreset
bind dcc n greetstatus dcc:greetstatus
bind dcc n|n gmotd dcc:gmotd
bind dcc n|n +greetnick dcc:+greetnick
bind dcc n|n -greetnick dcc:-greetnick
bind dcc n|n greethelp dcc:greethelp
bind dcc n|n greet dcc:greet
bind dcc n|n greethow dcc:greethow
bind dcc n|n greetwho dcc:greetwho
bind dcc n|n greetview dcc:greetview
bind dcc n|n +greet dcc:+greet
bind dcc n|n -greet dcc:-greet

set greet(version) "1.0.3"

proc wsg { string } {
global greet
putlog "GreetWondeR $greet(version) $string"
}

proc getvar { varname } {
global greet
set datafile [open $greet(dir)/$greet(data) r]
while {![eof $datafile]} {
  set datainhalt "[gets $datafile]"
  set pattern [string tolower [lindex $datainhalt 0]]
    if {$pattern == $varname} {
      set varname "[lrange $datainhalt 2 end]"
      }
    }
close $datafile
return $varname
}

proc savevar { string } {
global greet 
set varnamesave [lindex $string 0]
set value [lrange $string 1 end]
set file [open $greet(dir)/$greet(data) r]
while {![eof $file]} {
  set line [gets $file]
  if {[lindex $line 0] != $varnamesave} {
    lappend datalist $line
    }
  }
close $file
set file [open $greet(dir)/$greet(data) w]
foreach line $datalist {
  if {![llength $line] < 1} {
    puts $file $line
    }
  }
puts $file "$varnamesave = $value"
close $file
return 1
}

proc getchannels {} {
global chanfile
set channels ""
set file [open $chanfile r]
while {![eof $file]} {
  set line [gets $file]
  if {$line != ""} {
    if {![string match "#*" $line]} {
      append channels "[lindex $line 2] "
      }
    }
  }
close $file
return $channels
}    

proc init { what idx } {
global greet nickgreets changreets
if {![file exists $greet(dir)]} {
  if {$what == "start"} { 
    wsg "Can't find $greet(dir)...creating..."
    }
  exec mkdir $greet(dir)
  }
if {![file exists $greet(dir)/$greet(data)]} {
  if {$what == "start"} {
    wsg "Can't find $greet(data)...creating..."
    }
  }
if {![file exists $greet(dir)/$greet(data)]} {
  set file [open $greet(dir)/$greet(data) w]
  puts $file "# TCL: GreetWondeR $greet(version)"
  puts $file "# Created on [date] at [time]"
  puts $file "greet(how) = $greet(how)"
  foreach chan [getchannels] {
    set chan [string tolower $chan]
    puts $file "greet($chan) = 0"
    puts $file "greetall($chan) = $greet(all)"
    puts $file "greethow($chan) = $greet(how)"
    }
  close $file
  } else {
  set file [open $greet(dir)/$greet(data) r]
  set line [gets $file]
  set oldver [lrange $line 2 3]
  close $file
  if {[lindex $oldver 1] != $greet(version)} {
    if {$what == "start"} { wsg "Found old data ($oldver)...updating..." }
    set gnew ""
    set file [open $greet(dir)/$greet(data) r]
    while {![eof $file]} {
      set line [gets $file]
      if {[llength $line] > 1} {
        if {![string match "#*" $line]} {
          lappend gnew $line
          }
        }
      }
    close $file
    set file [open $greet(dir)/$greet(data) w]
    puts $file "# TCL: GreetWondeR $greet(version)"
    puts $file "# Created on [date] at [time]"
    foreach line $gnew {
      puts $file $line
      }
    close $file
    }
  }
set gcreated ""
foreach chan [getchannels] {
  set gfile "$greet(dir)/[string trimleft [string tolower $chan] #].dat"
  set changreets([string tolower $chan]) ""
  if {![file exists $gfile]} {
    set file [open $gfile w]
    close $file
    append gcreated "$chan "
    } else {
    set file [open $gfile r]
    while {![eof $file]} {
      set line [gets $file]
      if {$line != ""} {
        lappend changreets([string tolower $chan]) $line
       }
     }
    close $file
    }
  }
if {$gcreated != ""} {
  if {$what == "reset"} {
    putdcc $idx "Created greetfile for: $gcreated"
    } else {
    wsg "Created greetfile for: $gcreated"
    }
  }
if {[file exists $greet(dir)/$greet(nicks)]} {
  set file [open $greet(dir)/$greet(nicks) r]
  set nickgreets ""
  while {![eof $file]} {
    set line [gets $file]
    if {[llength $line] > 1} {
      lappend nickgreets $line
      }
    }
  close $file
  } else {
  set nickgreets ""
  }
}

init start 0 

bind chon n|n * motd:greet
proc motd:greet { handle idx } {
global greet
set handle [string tolower $handle]
set greetmotd [getvar motd($handle)]
if {$greetmotd == 0} {
  return 0
  }
putdcc $idx "This Bot is using YAGreeT $greet(version)"
putdcc $idx "Try .greethelp for a list of commands"
putdcc $idx "(to deactivate this message, try .gmotd off)"
putdcc $idx " "
}

proc dcc:gmotd { handle idx arg } {
if {[llength $arg] < 1} {
  putdcc $idx "Usage: .gmotd <on/off>"
  return 0
  }
set handle [string tolower $handle]
set arg [string tolower $arg]
if {$arg == "on"} {
  savevar "motd($handle) 1"
  putdcc $idx "GreetWondeR MOTD turned on."
  return 0
  }
if {$arg == "off"} {
  savevar "motd($handle) 0"
  putdcc $idx "GreetWondeR MOTD turned off."
  return 0
  }
putdcc $idx "Usage: .gmotd <on/off>"
}

	   
proc dcc:greetreset { handle idx arg } {
global greet
putlog "#$handle# greetreset"
putdcc $idx "Resetting GreetWondeR..."
exec rm -rf $greet(dir)
init reset $idx
putdcc $idx "Done, tcl successfully resetted."
}

proc dcc:greetstatus { handle idx chan } {
global greet flood
set greethow [getvar greet(how)]
putlog "#$handle# greetstatus"
putdcc $idx "I am GreetWondeR.tcl, running Version $greet(version)."
putdcc $idx " "
putdcc $idx "Saving data in: $greet(dir)/$greet(data)."
putdcc $idx "Saving greetnicks in: $greet(dir)/$greet(nicks)."
putdcc $idx " "
putdcc $idx "Standard settings:"
if {$greet(all) == 1} { set a "all" } 
if {$greet(all) == 2} { set a "known" } 
if {$greet(all) == 0} { set a "unkown" }
putdcc $idx "  - greeting $a users"
putdcc $idx "  - allowing $greet(max) lines for greets"
putdcc $idx "  - greets via $greethow"
set joins [lindex [split $flood(time) :] 0]
set secs [lindex [split $flood(time) :] 1]
putdcc $idx " "
putdcc $idx "Flood settings:"
putdcc $idx "  - $joins joins in $secs secs"
putdcc $idx "  - Shutdown for $greet(noresponse) mins"
set count 0
if {![file exists $greet(dir)/$greet(nicks)]} {
  putdcc $idx " "
  putdcc $idx "There are currently no nick-greets saved."
  } else {
  set file [open $greet(dir)/$greet(nicks) r]
  while {![eof $file]} {
    set line [gets $file]
    if {[llength $line] > 1} {
      incr count
      }
    }
  close $file
  putdcc $idx " "
  if {$count == 1} {
    putdcc $idx "There is currently 1 nick-greet saved."
    } {
    putdcc $idx "There are currently $count nick-greets saved."
    }
  }
putdcc $idx " "
if {[llength $chan] < 1} {
  set chan [lindex [console $idx] 0]
  } else {
  if {![validchan $chan]} {
    return 0
    }
  }
putdcc $idx "Dynamic Settings for $chan:"
set chan [string tolower $chan]
set greetload "$greet(dir)/[string trimleft $chan #].dat"
if {![file exists $greetload]} {
    set file [open $greetload w]
    close $file
    }
set count 0
set file [open $greetload r]
while {![eof $file]} {
  set line [gets $file]
  if {[llength $line] > 1} {
    incr count
    }
  }
close $file
set greetall [getvar greetall($chan)]
set greethow [getvar greethow($chan)]
if {[getvar greet($chan)] == 1} { set b "disabled" } { set b "enabled" } 
putdcc $idx "  - Greets are currently $b"
if {$greetall == 1} { set c "all" }
if {$greetall == 2} { set c "known" }
if {$greetall == 0} { set c "unkown" }
putdcc $idx "  - Showing to $c users"
putdcc $idx "  - via $greethow"
putdcc $idx "  - There are currently $count greetlines saved"
if {$count != "0"} {
  putdcc $idx " "
  putdcc $idx "For a list of greets on $chan, try .greetview $chan."
  }
}

proc dcc:+greetnick { handle idx arg } {
global greet nickgreets
if {[llength $arg] < 3} {
  putdcc $idx "Usage: .+greetnick <handle> <msg/notice/pub> <text>"
  return 0
  }
set nick [lindex $arg 0]
set how [string tolower [lindex $arg 1]]
if {$how == "msg"} { 
  set how "PRIVMSG"
  } else {
if {$how == "notice"} {
   set how "NOTICE"
  } else {
if {$how == "pub"} {
  set how "PUBLIC"
  } else {
    putdcc $idx "ERROR: Don't know, how to greet via $how. Only msg, notice or"
    putdcc $idx "pub is allowed."
    return 0
    }
  }
}
set text [lrange $arg 2 end]
if {![validuser $nick]} {
  putdcc $idx "I don`t know $nick. Only nicks, which are in the userlist, are allowed!"
  return 0
  }  
if {![file exists $greet(dir)/$greet(nicks)]} {
  set file [open $greet(dir)/$greet(nicks) w]
  puts $file "$nick $how $text"
  close $file
  } else {
  set file [open $greet(dir)/$greet(nicks) r]
  while {![eof $file]} {
    set line [gets $file]
    if {[llength $line] > 1} {
      if {[string match "$nick" [lindex $line 0]]} {
        putdcc $idx "Already a greetline for $nick saved:"
	putdcc $idx "[lrange $line 2 end]"
	close $file
	return 0
	}
      }
    }
  close $file
  set file [open $greet(dir)/$greet(nicks) a+]
  puts $file "$nick $how $text"
  close $file
  }
set nickgreets ""
set file [open $greet(dir)/$greet(nicks) r]
while {![eof $file]} {
  set line [gets $file]
  if {[llength $line] > 1} {
    lappend nickgreets $line
    }
  }
close $file
putdcc $idx "Now greeting $nick with \"$text\" via $how."
return 0
}

proc dcc:-greetnick { handle idx arg } {
global greet nickgreets
if {[llength $arg] < 1} {
  putdcc $idx "Usage: .-greetnick <nick>"
  return 0
  }
set nick [lindex $arg 0]
if {![validuser $nick]} {
  putdcc $idx "I don`t know $nick. Only nicks, which are in the userlist, are allowed!"
  return 0
  }
if {![file exists $greet(dir)/$greet(nicks)]} {
  putdcc $idx "No individual greets are saved..."
  return 0
  }
putlog "#$handle# -greetnick $arg"
set file [open $greet(dir)/$greet(nicks) r]
set tmp ""
while {![eof $file]} {
  set line [gets $file]
  if {[llength $line] > 1} {
    if {![string match "$nick *" $line]} {
      lappend tmp $line
      }
    }
  }
close $file
if {$tmp == ""} { 
  exec rm $greet(dir)/$greet(nicks)
  set nickgreets ""
  } else {
  set file [open $greet(dir)/$greet(nicks) w]
  foreach line $tmp {
    puts $file $line
    }
  close $file
  }
set nickgreets ""
set file [open $greet(dir)/$greet(nicks) r]
while {![eof $file]} {
  set line [gets $file]
  if {[llength $line] > 1} {
    lappend nickgreets $line
    }
  }
close $file
putdcc $idx "Deleted greet for $nick"
return 0
}

proc dcc:greethelp { handle idx arg } {
global greet
set arg "[string tolower $arg]"
if {[string match ".*" $arg]} { set arg [string trimleft $arg .] }
putlog "#$handle# greethelp $arg"
if {$arg == "greetreset"} {
  putdcc $idx "### greetreset"
  putdcc $idx "    Removes _all_ files, created by GreetWondeR and then"
  putdcc $idx "    restartes the script..."
  putdcc $idx "    WARNING: All greets will be lost after a .greetreset!"
  return 0
  }
if {$arg == "+greetnick"} {
  putdcc $idx "### +greetnick <handle> <msg/notice/pub> <text>"
  putdcc $idx "   Adds a greet (<text>) for <nick>."
  putdcc $idx "   Only known nicks (userlist) are allowed."
  putdcc $idx "   NOTE: Only 1 line is allowed."
  putdcc $idx " "
  putdcc $idx "   Example:"
  putdcc $idx "   .+greetnick Wingman msg Hi Wing, what's up?"
  return 0
  }
if {$arg == "-greetnick"} {
  putdcc $idx "### -greetnick <nick>"
  putdcc $idx "   Dels the greet for <nick>."
  putdcc $idx " "
  putdcc $idx "   Example:"
  putdcc $idx "   .-greetnick Wingman"
  return 0
  }
if {$arg == "greetnickview"} {
  putdcc $idx "### greetnickview"
  putdcc $idx "    Shows a list of nick-greets."
  return 0
  }
if {$arg == "+greet"} {
  putdcc $idx "### +greet \[channel\] \[flag\] <text>"
  putdcc $idx "   Adds a greetline for \[channel\]."
  putdcc $idx "   |nick| and |chan| are replaced by the proc vars, e.g."
  putdcc $idx "   if Wingman joins #Eggdrop, he will see instead of |nick|"
  putdcc $idx "   and |chan| - Wingman and #Eggdrop."
  putdcc $idx "   Validflags are: +n, +m, +o and +f"
  putdcc $idx " "
  putdcc $idx "   Example:"
  putdcc $idx "   .+greet Welcome |nick| to |chan|"
  putdcc $idx "   .+greet #eggdrop Welcome |nick| to |chan|"
  putdcc $idx "   .+greet +n Welcome, you are a owner of this chan"
  putdcc $idx " "
  putdcc $idx "See also: -greet, greetview"
  return 0
  }
if {$arg == "-greet"} {
  putdcc $idx "### -greet \[channel\] \[flag\] <text>"
  putdcc $idx "   Deletes a greetline from \[channel\]."
  putdcc $idx " "
  putdcc $idx "   Example:"
  putdcc $idx "   .-greet Welcome |nick| to |chan|"
  putdcc $idx "   .-greet #eggdrop Welcome |nick| to |chan|"
  putdcc $idx "   .-greet +n Welcome, you are a owner of this chan"
  putdcc $idx " "
  putdcc $idx "See also: +greet, greetview"
  return 0
  }
if {$arg == "greetview"} {
  putdcc $idx "### greetview \[channel\]"
  putdcc $idx "   Shows the greets for \[channel\]."
  putdcc $idx " "
  putdcc $idx "   Example:"
  putdcc $idx "   .greetview"
  putdcc $idx "   .greetview #eggdrop"
  putdcc $idx "See also: +greet, -greet"
  return 0
  }
if {$arg == "greet"} {
  putdcc $idx "### greet \[channel\] <on/off>"
  putdcc $idx "   Enables/disables greets for \[channel\]."
  putdcc $idx " "
  putdcc $idx "   Example:"
  putdcc $idx "   .greet on"
  putdcc $idx "   .greet #eggdrop on"
  putdcc $idx "See also: greetwho, greethow, greetview"
  return 0
  }
if {$arg == "greetwho"} {
  putdcc $idx "### greetwho \[channel\] <all/known/unknown>"
  putdcc $idx "   Show greets to all, only known users or"
  putdcc $idx "   only unknown users?"
  putdcc $idx " "
  putdcc $idx "   Example:"
  putdcc $idx "   .greetwho all"
  putdcc $idx "   .greetwho #eggdrop all"
  putdcc $idx "See also: greet, greethow, greetview"
  return 0
  }
if {$arg == "greethow"} {
  putdcc $idx "### greethow \[channel\] <notice/privmsg>"
  putdcc $idx "   Should i greet users by NOTICE or PRIVMSG (MSG)?"
  putdcc $idx " "
  putdcc $idx "   Example:"
  putdcc $idx "   .greethow notice"
  putdcc $idx "   .greethow #eggdrop notice"
  putdcc $idx "See also: greet, greetwho, greetview"
  return 0
  }
if {$arg == "gmotd"} { 
  putdcc $idx "### gmotd <on/off>"
  putdcc $idx "   Turns on/off the startupmsg \"This Bot is using...\""
  return 0
  }
if {$arg == "guide"} {
  putdcc $idx "A short guide for GreetWonder $greet(version) (c) Wingman 1999"
  putdcc $idx " "
  putdcc $idx "1. If you want to add a greet for #test, which should get all users..."
  putdcc $idx "   .+greet #test Hi (nick) - Welcome to (chan)"
  putdcc $idx "   .greetwho #test all"
  putdcc $idx " "
  putdcc $idx "2. If you want flag specific greets, try..."
  putdcc $idx "   .+greet #test +n Hi (nick) - You are an Owner on (chan)"
  putdcc $idx " "
  putdcc $idx "3. If you want to greet a nick with a specific line, then use..."
  putdcc $idx "   .+greetnick Nickname pub Hi Nick, what's up?"
  putdcc $idx "   (Only nicknames, which are in the userlist are allowed)"
  putdcc $idx " "
  putdcc $idx "4. A feature of this tcl is its varreplacing:"
  putdcc $idx "   (nick), (chan) and (botnick) are replaced by the tcl vars,"
  putdcc $idx "   which means, if let's say Wingman joins #Eggdrop and the Botnick"
  putdcc $idx "   is Eggie, he will see (if there's greet like"
  putdcc $idx "   Hi (nick) - Welcome to (chan) - For a help try /msg (botnick) help"
  putdcc $idx "   Hi Wingman - Welcome to #Eggdrop - For a help try /msg Eggie help"
  putdcc $idx " "
  putdcc $idx "BTW: You can add up to $greet(max) lines for a greet, but just 1 line"
  putdcc $idx "for a nickgreet."
  return 0
  }
putdcc $idx "Help for TCL: GreetWondeR $greet(version) (c) Wingman 1999"
putdcc $idx " "
putdcc $idx "If you want to add or del greets, use:"
putdcc $idx " .+/-greet \[channel\] \[flag\] <text>"
putdcc $idx " .+greetnick <nick> <msg/notice/pub> <text>"
putdcc $idx " .-greetnick <nick>"
putdcc $idx " "
putdcc $idx "If you want to see the greets, use:"
putdcc $idx " .greetview \[channel\]                        .greetnickview"
putdcc $idx " "
putdcc $idx "If you want to change the settings for greets, use:"
putdcc $idx " .greethow \[channel\] <notice/privmsg>"
putdcc $idx " .greetwho \[channel\] <all/known/unknown>"
putdcc $idx " .greet \[channel\] <on/off>"
putdcc $idx " "
putdcc $idx "Other Commands:"
putdcc $idx " .greetreset                                 .gmotd <on/off>"
putdcc $idx " .greetstatus \[channel\]"
putdcc $idx " "
putdcc $idx "If you want a short guide to GreetWonder.tcl, use '.greethelp guide'"
putdcc $idx " "
putdcc $idx "Words in \[ \] are options and not neccessary."
putdcc $idx " "
putdcc $idx "You can get help on individual commands: '.greethelp <command>'"
return 0
}

proc dcc:greetnickview { handle idx arg } {
global greet
putlog "#$handle# greetnickview"
if {![file exists $greet(dir)/$greet(nicks)]} {
  putdcc $idx "No individual greets saved..."
  return 0
  }
putdcc $idx "Showing individual greets:"
set file [open $greet(dir)/$greet(nicks) r]
while {![eof $file]} {
  set line [gets $file]
  if {[llength $line] > 1} {
    set nick [lindex $line 0]
    set how [lindex $line 1]
    set text [lrange $line 2 end]
    putdcc $idx "$nick ($how): $text"
    }
  }
}
 
proc dcc:greet { handle idx arg } {
global greet
if {[llength $arg] < 1} {
  putdcc $idx "Usage: .greet \[channel\] <on/off>"
  return 0
  }
set greet(chan) ""
set greet(what) ""
set greet(flags) ""
if {[string match "#*" $arg]} {
    set greet(chan) [string tolower [lindex $arg 0]]
    set greet(what) [lrange $arg 1 end]
    if {![validchan $greet(chan)]} {
      putdcc $idx "ERROR: I'm not on $greet(chan)"
      return 0
      }
    } else {
    set greet(what) [string tolower $arg]
    set greet(chan) [string tolower [lindex [console $idx] 0]]
    }
if {![matchattr $handle n]} {
  if {![matchchanattr $handle |n $greet(chan)]} {
    putdcc $idx "Sorry, you're not chanowner on $greet(chan)"
    return 0
    }
  }
putlog "#$handle# greet ($greet(chan)) $greet(what)"
if {$greet(what) == "on"} {
  savevar "greet($greet(chan)) 1"
  putdcc $idx "Greets for $greet(chan) are now enabled"
  return 0
  }
if {$greet(what) == "off"} {
  savevar "greet($greet(chan)) 0"
  putdcc $idx "Greets for $greet(chan) are now disabled"
  return 0
  }
putdcc $idx "Usage: .greet \[channel\] <on/off>"
}

proc dcc:greethow { handle idx arg } {
if {[llength $arg] < 1} {
  putdcc $idx "Usage: .greethow \[channel\] <NOTICE/PRIVMSG>"
  return 0
  }
if {[string match "#*" $arg]} {
    set greet(what) [string tolower [lrange $arg 1 end]]
    set greet(chan) [string tolower [lindex $arg 0]]
    if {![validchan $greet(chan)]} {
      putdcc $idx "ERROR: I'm not on $greet(chan)"
      return 0
      }
    } else {
    set greet(what) [string tolower $arg]
    set greet(chan) [string tolower [lindex [console $idx] 0]]
    }
if {![matchattr $handle n]} {
  if {![matchchanattr $handle |n $greet(chan)]} {
    putdcc $idx "Sorry, you're not chanowner on $greet(chan)"
    return 0
    }
  }
putlog "#$handle# greethow $arg"
if {$greet(what) == "notice"} {
  savevar "greethow($greet(chan)) NOTICE"
  putdcc $idx "Now greeting users on $greet(chan) by NOTICE"
  return 0
  }
if {$greet(what) == "privmsg" || $greet(what) == "msg"} {
  savevar "greethow($greet(chan)) PRIVMSG"
  putdcc $idx "Now greeting users on $greet(chan) by PRIVMSG"
  return 0
  }
putdcc $idx "Usage: .greethow \[channel\] <NOTICE/PRIVMSG>"
}

proc dcc:greetwho { handle idx arg } {
if {[llength $arg] < 1} {
  putdcc $idx "Usage: .greetwho \[channel\] <all/known/unkown>"
  return 0
  }
if {[string match "#*" $arg]} {
    set greet(what) [string tolower [lrange $arg 1 end]]
    set greet(chan) [string tolower [lindex $arg 0]]
    if {![validchan $greet(chan)]} {
      putdcc $idx "ERROR: I'm not on $greet(chan)"
      return 0
      }
    } else {
    set greet(what) [string tolower $arg]
    set greet(chan) [string tolower [lindex [console $idx] 0]]
    }
if {![matchattr $handle n]} {
  if {![matchchanattr $handle |n $greet(chan)]} {
    putdcc $idx "Sorry, you're not chanowner on $greet(chan)"
    return 0
    }
  }
putlog "#$handle# greetwho ($greet(chan)) $greet(what)"
if {$greet(what) == "all"} {
  savevar "greetall($greet(chan)) 1"
  putdcc $idx "Now showing greets on $greet(chan) to all users"
  return 0
  }
if {$greet(what) == "known"} {
  savevar "greetall($greet(chan)) 0"
  putdcc $idx "Now showing greets on $greet(chan) to only known users"
  return 0
  }
if {$greet(what) == "unknown"} {
  savevar "greetall($greet(chan)) 2"
  putdcc $idx "Now showing greets on $greet(chan) to only unknown users"
  return 0
  }
putdcc $idx "Usage: .greetwho \[channel\] <all/known/unknown>"
}

proc dcc:greetview { handle idx arg } {
global greet
if {[llength $arg] < 1} {
  set chan [string tolower [lindex [console $idx] 0]]
  } else {
  set chan [string tolower [lindex $arg 0]]
  }
if {![validchan $chan]} {
  putdcc $idx "ERROR: I'm not on $chan"
  return 0
  }
putlog "#$handle# ($chan) greetview"
set greetload "$greet(dir)/[string tolower [string trimleft $chan #]].dat"
set greetchan [getvar greet($chan)]
set greetallchan [getvar greetall($chan)]
set greethowchan [getvar greethow($chan)]
if {$greetchan == 0} {
  set a "disabled"
  } else {
  set a "enabled"
  }
if {$greetallchan == 0} {
  set c "all"
  }
if {$greetallchan == 1} {
  set c "only known"
  }
if {$greetallchan == 2} {
  set c "only unkown"
  }
putdcc $idx "Greets for $chan are currently $a, showing via $greethowchan."
if {![file exists $greetload]} {
    set file [open $greetload w]
    close $file
    return 0
    }
set greetstore ""
set file [open $greetload r]
while {![eof $file]} {
  set line [gets $file]
  if {$line != ""} {
    lappend greetstore $line
    }
  }
close $file
set greeta ""
set greetb ""
foreach line $greetstore {
  if {[string match "+*" $line]} {
    lappend greetflag([lindex $line 0]) [lrange $line 1 end]
    if {[lsearch -exact $greeta [lindex $line 0]] == -1} {
      append greeta "[lindex $line 0] "
      }
    } else {
    lappend greetb $line
    }
  }
if {$greeta != ""} {
  foreach flag $greeta {
    putdcc $idx "Greets for $flag users:"
    foreach line $greetflag($flag) {
      putdcc $idx "  - $line"
      }
    }
  }
if {$greetb != ""} {
putdcc $idx "Greets for $c users:"
foreach line $greetb {
  putdcc $idx "  - $line"
  }
}
}

proc dcc:+greet { handle idx arg } {
global greet changreets
if {[llength $arg] < 1} {
  putdcc $idx "Usage: .+greet \[channel\] \[+flag\] <greet>"
  return 0
  }
if {[llength $arg] < 2} {
  if {[string match "#*" $arg]} {
    putdcc $idx "Usage: .+greet \[channel\] \[+flag\] <greet>"
    return 0
    }
  }
set greetflags ""
if {[string match "#*" $arg]} {
  if {[string match "+*" [lindex $arg 1]]} {
    set greethow [lrange $arg 2 end]
    set greetflags [lindex $arg 1]
    set greetchan [lindex $arg 0]
    } else {
    set greethow [lrange $arg 1 end]
    set greetchan [lindex $arg 0]
    }
  if {![validchan $greetchan]} {
    putdcc $idx "ERROR: I'm not on $greetchan"
    return 0
    }
  } else {
  if {[string match "+*" [lindex $arg 0]]} {  
    set greethow [lrange $arg 1 end]
    set greetflags [lindex $arg 0]
    set greetchan [lindex [console $idx] 0]
    } else {
    set greethow $arg
    set greetchan [lindex [console $idx] 0]
    }
  }
if {![matchattr $handle n]} {
  if {![matchchanattr $handle |n $greet(chan)]} {
    putdcc $idx "Sorry, you're not chanowner on $greetchan"
    return 0
    }
  }
if {[string length $greetflags] > 2} {
  putdcc $idx "ERROR: only 1 flag is allowed, e.g. +greet +n <greet>"
  return 0
  }
if {$greetflags != ""} {
  putlog "#$handle# +greet ($greetchan) ($greetflags) $greethow"
  } else {
  putlog "#$handle# +greet ($greetchan) $greethow"
  }
set greetsave "$greet(dir)/[string tolower [string trimleft $greetchan #]].dat"
set count 0
if {[file exists $greetsave]} {
  set file [open $greetsave r]
  while {![eof $file]} {
    set line [gets $file]
    if {$line != ""} {
      if {$greetflags != ""} {
        if {[string match "$greetflags *" $line]} {
          incr count
          }
        } else {
        incr count
        }
      }
    }
  close $file
  } else {
  set file [open $greetsave w]
  if {$greetflags == ""} {
    puts $file $greethow
    } else {
    puts $file "$greetflags $greethow"
    }
  close $file
  }
if {$count >= $greet(max)} {
  putdcc $idx "ERROR: Only $greet(max) lines are allowed for greets."
  return 0
  }
set file [open $greetsave a+]
if {$greetflags == ""} {
  puts $file $greethow
  } else {
  puts $file "$greetflags $greethow"
  }
close $file
if {$greetflags != ""} {
  putdcc $idx "Added $greethow ($greetflags users) for $greetchan"
  } else {
  putdcc $idx "Added $greethow for $greetchan"
  }
set changreets([string tolower $greetchan]) ""
putlog $greetsave
set file [open $greetsave r]
while {![eof $file]} {
  set line [gets $file]
  if {$line != ""} {
    lappend changreets([string tolower $greetchan]) $line
    }
  }
close $file
putlog "changreets == $changreets([string tolower $greetchan])"
}

bind bot - sg_update bot:sg_update 
proc bot:sg_update { bot com newver } {
set notetxt "GreetWondeR.tcl: Update to $newver is available at http://defiant.vilstal.net/~wingman"
foreach user [userlist n] {
  if {[notes $user] < 10} {
    sendnote "Wingman@$bot" $user $notetxt
    }
  }
}

bind bot - sg_info bot:sginfo
proc bot:sginfo { bot com arg } {
global greet
putbot $bot "sg_version $greet(version)"
}

proc dcc:-greet { handle idx arg } {
global greet changreets
if {[llength $arg] < 1} {
  putdcc $idx "Usage: .-greet \[channel\] <greet>"
  return 0
  }
if {[llength $arg] < 2} {
  if {[string match "#*" $arg]} {
    putdcc $idx "Usage: .-greet \[channel\] <greet>"
    return 0
    }
  }
if {[string match "#*" $arg]} {
  set greethow [lrange $arg 1 end]
  set greetchan [lindex $arg 0]
  if {![validchan $greetchan]} {
    putdcc $idx "ERROR: I'm not on $greetchan"
    return 0
    }
  } else {
  set greethow $arg
  set greetchan [lindex [console $idx] 0]
  }
if {![matchattr $handle n]} {
  if {![matchchanattr $handle |n $greetchan]} {
    putdcc $idx "Sorry, you're not chanowner on $greetchan"
    return 0
    }
  }
set greetsave "$greet(dir)/[string tolower [string trimleft $greetchan #]].dat"
if {![file exists $greetsave]} {
  putdcc $idx "ERROR: No greets set for $greetchan"
  return 0
  }
putlog "#$handle# -greet ($greetchan) $greethow"
set greetnew ""
set greetfound 0
set file [open $greetsave r] 
while {![eof $file]} {
  set line [gets $file]
  if {![llength $line] < 1} {
    if {[string match "$greethow*" $line]} {
      set greetfound 1
      } else {
      lappend greetnew $line
      }
    }
  }
close $file
if {$greetfound == 0} {
  putdcc $idx "Can't find $greethow for $greetchan"
  return 0
  }
if {[llength $greetnew] < 1} {
  putdcc $idx "Deleted greets for $greetchan"
  return 0
  }
set file [open $greetsave w]
foreach line $greetnew {
  puts $file $line
  }
close $file
set changreets([string tolower $greetchan])
set file [open $greetsave r]
while {![eof $file]} {
  set line [gets $file]
  if {[llength $line] > 1} {
    lappend changreets([string tolower $greetchan]) $line
    }
  }
close $file
putdcc $idx "Deleted $greethow for $greetchan"
}

if {$greet(floodprotect) == 1} {
  set joins [lindex [split $flood(time) :] 0]
  set secs [lindex [split $flood(time) :] 1]
  wsg "Flood: ($joins joins in $secs secs - Shutdown for $greet(noresponse) mins)"
  bind join - *!*@* greet:flood
  proc greet:flood { nick uhost handle chan } {
  global flood botnick
  if {$botnick == $nick} { return 0 }
  set joins [lindex [split $flood(time) :] 0]
  set secs [lindex [split $flood(time) :] 1]
  set chan [string tolower $chan]
  if {![info exists flood($chan)]} {
    set flood($chan) 0
    }
  incr flood($chan)
  if {$flood($chan) >= $joins} {
    greet:isflood $chan $flood($chan) $secs
    return 0
    }
  if {![info exists flood(timer)]} {
    set flood(timer) [utimer $secs "greet:resetflood $chan $flood($chan) $secs"]
    }
  }
 
  proc greet:resetflood { chan fjoins secs} {
  global flood
  unset flood($chan)
  unset flood(timer)
  }

  proc greet:isflood { chan fjoins secs} {
  global greet
  wsg "WARNING: Floodjoins detected at $chan ($fjoins joins in < $secs secs)"
  wsg "Shutting down all greet replys..."
  unbind join - *!*@* greet:join
  unbind join - *!*@* greet:flood
  timer $greet(noresponse) "greet:startup $chan"
  }
  
  proc greet:startup { chan } {
  wsg "Flood ($chan) seems to be over...restarting greets..."
  bind join - *!*@* greet:join
  bind join - *!*@* greet:flood
  }
}

proc greet:sucks { nick chan line } {
global botnick
while {[string match "* (nick) *" $line] || [string match "* (nick)" $line] || [string match "(nick) *" $line]} {
  set found [lsearch -exact $line "(nick)"]
  set line [lreplace $line $found $found $nick]
  }
while {[string match "* (chan) *" $line] || [string match "* (chan)" $line] || [string match "(chan) *" $line]} {
  set found [lsearch -exact $line "(chan)"]
  set line [lreplace $line $found $found $chan]
  }
while {[string match "* (botnick) *" $line] || [string match "* (botnick)" $line] || [string match "(botnick) *" $line]} {
  set found [lsearch -exact $line "(botnick)"]
  set line [lreplace $line $found $found $botnick]
  }
return $line
}

bind join - *!*@* greet:join
proc greet:join { nick uhost handle chan } {
global greet botnick nickgreets changreets
if {$nick == $botnick || [matchattr $handle b]} {
  return 0
  }
set greetchan [getvar greet($chan)]
if {$greetchan == 0} {
  return 0
  }
if {$handle != "*"} {
  if {$nickgreets != ""} {
    foreach line $nickgreets {    
      if {[string match "$handle *" $line]} {
        set how [lindex $line 1]
        set text [lrange $line 2 end]
        if {$how != "PUBLIC"} {
          puthelp "$how $nick :$text"
          return 0
          } {
          putchan $chan "$text"
          return 0
          }
        }
      }
    }
  }
if {![info exists changreets([string tolower $chan])]} {
  return 0
  }
if {$changreets([string tolower $chan]) == ""} { 
  return 0
  }
set greethow [getvar greethow([string tolower $chan])]
set greetstore ""
foreach line $changreets([string tolower $chan]) {
  lappend greetstore $line
  }
set greeta ""
foreach line $greetstore {
  if {[string match "+*" $line]} {
    lappend greetflag([lindex $line 0]) [lrange $line 1 end]
    if {[lsearch -exact $greeta [lindex $line 0]] == -1} {
      append greeta "[lindex $line 0] "
      }
    } else {
    lappend greetb $line
    }
  }
if {$greeta != ""} {
  foreach flag $greeta {
    if {[matchattr $handle $flag] || [matchchanattr $handle |$flag $chan]} {
      foreach line $greetflag($flag) {
        puthelp "$greethow $nick :[greet:sucks $nick $chan $line]"
        }
      return 0
      }
    }
  }  
set greetallchan [getvar greetall([string tolower $chan])]
if {$greetallchan == 0} {
  if {$handle == "*"} {
    return 0
    }
  }
if {$greetallchan == 2} {
  if {$handle != "*"} {
    return 0
    }
  }
if {$greetb != ""} {
  foreach line $greetb {
    puthelp "$greethow $nick :[greet:sucks $nick $chan $line]"
    }
  return 0
  }
}

set greet_loaded 1
wsg "by Wingman (c) 1999 loaded (.greethelp for help)."
