#by wiebe @ QuakeNet
#requires whox.tcl


set c_adduser(xhost) "users.quakenet.org"



#help adduser msg
bind msgm mn "help adduser" c_adduser:help:msg

proc c_adduser:help:msg { nick uhost handle text } {
  lappend output "Usage: adduser <nick>|<#account> \[<host1> <host2> .. <hostN>\]"
  lappend output "Adds nick's account or #account given to the bot, optional with the hostmasks specified, *!*@<account>.$::c_adduser(xhost) is added by default."
  if { [catch {set x [cnotice $nick $output]} error] || !$x } {
    foreach t $output { puthelp "NOTICE $nick :$t" }
  }
  putcmdlog "($nick!$uhost) !$handle! $text"
}



#adduser msg
bind msg mn adduser c_adduser:msg

proc c_adduser:msg { nick uhost handle text } {
  set target [lindex [split $text] 0]
  set targethand [nick2hand $target]
  if { [string equal $targethand *] } { set targethand "" }
  if { [string match \#* $target] } {
    set account [string range $target 1 end]
  } elseif { [catch {set account [whox $target a]} error] } {
    putlog "ERROR using whox.tcl, perhaps you have not loaded it?"
    error $error
  }
  if { [string equal $account 0] } { set account "" }
  if { [string equal $target ""] || [string equal $target \#] } {
    lappend output "Usage: adduser <nick>|<#account> \[<host1> <host2> .. <hostN>\]"
  } elseif { ![string equal $targethand ""] && ![string match \#* $target] } {
    lappend output "User $target already known as $targethand."
  } elseif { ![onchan $target] && ![string match \#* $target] } {
    lappend output "User $target is not in any of my channels."
  } elseif { [string equal $account ""] && ![string match \#* $target] } {
    lappend output "Account of user $target is not known."
  } elseif { [validuser $account] } {
    lappend output "Account $account is already added to this bot."
  } else {
    adduser $account
    set hosts "*!*@$account.$::c_adduser(xhost) [join [lrange [split $text] 1 end]]"
    foreach host [split $hosts] { if { [string match *?!*?@*? $host] } { setuser $account HOSTS $host } }
    set hosts [getuser $account HOSTS]
    if { ![string equal $hosts ""] } { set hosts " with hosts $hosts" }
    if { [string match \#* $target] } {
      lappend output "Added account $account$hosts"
    } else { lappend output "Added $target as $account$hosts" }
  }
  if { [catch {set x [cnotice $nick $output]} error] || !$x } {
    foreach t $output { puthelp "NOTICE $nick :$t" }
  }
  return 1
}

