#Chapter 11.7 Example Script v1.2 by _SunMar_.
#This script is part of the TCL Guide by Marijn van Zon
#which can be found on http://www.suninet.nl/.

#Objective: write a script that voices everyone who joins one
#of the two channels which are set in the beginning of the
#script in the same list and says "Welcome $nick!" in every
#channel, plus allows users to set their own greeting with
#the channel command !greeting.

#Set the auto-voice channels here.
set channels "#eggdrop #tcl"

#The script
if {![file exists greetings.db]} {
  set fs [open greetings.db w]
  puts $fs ""
  close $fs
}

bind join - * join:voice_and_greet
proc join:voice_and_greet { nick host hand chan } {
  global channels greeting
  if {$chan == [lindex $channels 0] || $chan == [lindex $channels 1]} {
    pushmode $chan +v $nick
  }
  set fs [open greetings.db r]
  set greeting ""
  set finished 0
  while {![eof $fs] && !$finished} {
    gets $fs line
    if {[lindex $line 0] == $nick} {
      set greeting "[lrange $line 1 end]"
      set finished 1
    }
  }
  if {$greeting != ""} {
    puthelp "PRIVMSG $chan :\[$nick\]: $greeting"
  } else {
    puthelp "PRIVMSG $chan :Welcome $nick!"
  }
  return 0
}

bind pub - "!greeting" pub:greeting
proc pub:greeting { nick user hand chan arg } {
  set greeting "$arg"
  if {$greeting == ""} {
    puthelp "PRIVMSG $nick :You have to supply the greeting you want to set."
    return 0
  }
  set dbfs [open greetings.db r]
  set tmpfs [open greetings.db.tmp w]
  set change 0
  while {![eof $dbfs]} {
    if {![gets $dbfs line]} {
      puts $tmpfs "$line"
    } elseif {[lindex $line 0] == $nick} {
      puts $tmpfs "$nick $greeting"
      set change 1
    }
  }
  if {!$change} {
    puts $tmpfs "$nick $greeting"
    puthelp "PRIVMSG $nick :Your greeting has been added."
  } else {
    puthelp "PRIVMSG $nick :Your greeting has been changed."
  }
  close $dbfs
  close $tmpfs
  set fs [open greetings.db.tmp r]
  set greetingsdb "[read $fs]"
  close $fs
  set fs [open greetings.db w]
  puts $fs "$greetingsdb"
  close $fs
  return 0
}

