#!/usr/bin/wishx
#
# hlclustermon
#
# Half-Life dedicated server cluster administration/monitoring GUI client
# Copyright (C) 2000 Rob Abbott
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
# Comments, bug reports, etc to linuxhlds@halflife.org
#
# Modification history:
#
#   rabbott 2000-11-15   - Check for Extended Tk
#
#   rabbott 2000-07-07   - Fixed "switch pattern with no body" error
#
#   rabbott 2000-06-29   - Release 1.10
#                        - Added 'refresh' button
#
#######################################################################
# About - just an info box 
#
proc aboutGui {} {
	global vers vnum font

	helpBox about \
"
This is a GUI-based Half-Life server administration tool for Linux.

Please send email if you encounter problems or have any comments!
linuxhlds@halflife.org

Visit Maelstrom's Brewpub (TFC/Linux)
63.68.143.63:27015


$vers, Copyright (C) 2000 Rob Abbott

$vers comes with ABSOLUTELY NO WARRANTY; for details see Help->Warranty

This is free software, and you are welcome to redistribute it
under certain conditions; see Help->Conditions for details.

\"Relax, don't worry, have a homebrew\"
   -- Charlie Papazian
"
}

proc warranty {} {

	helpBox warranty \
"
                            NO WARRANTY

  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.

  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
"
}

proc helpBox { wn text } {
	global vers font

	toplevel .$wn
	frame .$wn.log
	text .$wn.log.text -height 20 -state normal -fg yellow -bg black \
		-yscroll ".$wn.log.sy set" -font $font(norm)
	scrollbar .$wn.log.sy -command ".$wn.log.text yview"
	.$wn.log.text insert end $text

	.$wn.log.text configure -state disabled
	pack .$wn.log.text -side right
	pack .$wn.log.sy -side left -expand y -fill y
	frame .$wn.b
   	button .$wn.b.b1 -text "Dismiss" -command "destroy .$wn" -font $font(norm)
	pack .$wn.b.b1 -side bottom
	pack .$wn.b -side bottom
	pack .$wn.log  -side top

	centerWindow .$wn .
}

proc cdm {} {
	global vers

	helpBox cdm \
"
		    GNU GENERAL PUBLIC LICENSE
   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

  0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License.  The \"Program\", below,
refers to any such program or work, and a \"work based on the Program\"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language.  (Hereinafter, translation is included without limitation in
the term \"modification\".)  Each licensee is addressed as \"you\".

Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope.  The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.

  1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.

You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.

  2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:

    a) You must cause the modified files to carry prominent notices
    stating that you changed the files and the date of any change.

    b) You must cause any work that you distribute or publish, that in
    whole or in part contains or is derived from the Program or any
    part thereof, to be licensed as a whole at no charge to all third
    parties under the terms of this License.

    c) If the modified program normally reads commands interactively
    when run, you must cause it, when started running for such
    interactive use in the most ordinary way, to print or display an
    announcement including an appropriate copyright notice and a
    notice that there is no warranty (or else, saying that you provide
    a warranty) and that users may redistribute the program under
    these conditions, and telling the user how to view a copy of this
    License.  (Exception: if the Program itself is interactive but
    does not normally print such an announcement, your work based on
    the Program is not required to print an announcement.)
 
These requirements apply to the modified work as a whole.  If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works.  But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.

Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.

In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.

  3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:

    a) Accompany it with the complete corresponding machine-readable
    source code, which must be distributed under the terms of Sections
    1 and 2 above on a medium customarily used for software interchange; or,

    b) Accompany it with a written offer, valid for at least three
    years, to give any third party, for a charge no more than your
    cost of physically performing source distribution, a complete
    machine-readable copy of the corresponding source code, to be
    distributed under the terms of Sections 1 and 2 above on a medium
    customarily used for software interchange; or,

    c) Accompany it with the information you received as to the offer
    to distribute corresponding source code.  (This alternative is
    allowed only for noncommercial distribution and only if you
    received the program in object code or executable form with such
    an offer, in accord with Subsection b above.)

The source code for a work means the preferred form of the work for
making modifications to it.  For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable.  However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.

If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
 
  4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License.  Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.

  5. You are not required to accept this License, since you have not
signed it.  However, nothing else grants you permission to modify or
distribute the Program or its derivative works.  These actions are
prohibited by law if you do not accept this License.  Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.

  6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions.  You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.

  7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all.  For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.

If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.

It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices.  Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.

This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
 
  8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded.  In such case, this License incorporates
the limitation as if written in the body of this License.

  9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

Each version is given a distinguishing version number.  If the Program
specifies a version number of this License which applies to it and \"any
later version\", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation.  If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.

  10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission.  For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this.  Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
"
}

proc menuHelp {} {
	global vers

	helpBox menuhelp \
"$vers

==============================================================================

File Menu
   Connect All    : Connects to all servers you have configured.

   Disconnect All : Disconnects from all servers that you are currently
               		connected to. 

   -----------------------------------------------------------------

   Exit          : Disconnects you from all hlds_ld's and exits the GUI. 


==============================================================================

Options Menu
   Client Options

      Server List : A list of <name>:<port> entries, where:
                    <name> = The full hostname or IP address of the server
                    <port> = The port that hlds_ld is listening on, on
                    the specified server.

                    It's important that <name> and <port> be separated by
                    a colon, and each <name>:<port> entry be separated by
                    a space.
	
      Auth List   : List of authorization strings corresponding to the
                    server(s) configured above.

                    Each entry must be separated by a space. 
                    To specify an empty auth string, use curly braces \"{}\"

					Yes, this entry is cleartext.
					Yes, this entry is stored in a config file.

      Log History : The number of lines to store in the output window at
                    the bottom of the GUI.

      Log Height  : The number of lines visible in the output window at
                    the bottom of the GUI.
                    You may want to change this based on the size of your
                    display.

      Table Height: The number of lines visible in the users/ping/etc table
                    on the GUI.
                    You may want to change this based on the size of your
                    display.

      Font Size   : The size of the font to use for display purposes.

   -----------------------------------------------------------------

   Reset Alert = If an alert is present, reset it to green
"
}

proc buttonHelp {} {
	global vers

	helpBox buthelp \
"$vers

==============================================================================

Start / Stop Server
   Starts or stops the selected server, depending upon it's state.
   You must be authorized ADMINISTRATOR	to do this.

-----------------------------------------------------------------

Launch hlgui
	hlclustermon is by design a minimal interface.  If you need detailed
	control or monitoring over a particular server, select it and hit
	this button.

	Unix users:  the 'hlgui' script must be in your PATH.
	Windows users:  the 'wish.exe' file must be in your PATH.

-----------------------------------------------------------------

Refresh
	This will refresh all servers that you are connected to
	as an ADMINISTRATOR.
"
}

######################################################################
# start of net code

proc multiConnectToServer {{resched 0}} {
	global servers clientOpts waitSocks tcl_platform

	set plat $tcl_platform(platform)

	set needResched 0

	foreach idx [keylkeys servers] {
		keylget servers $idx svrInfo
		keylget svrInfo connected connected

		if !$connected {
			keylget svrInfo addr addr
			keylget svrInfo port port

			statusBar "Connecting to $addr:$port ... "
			update idletasks

			if [cequal $plat unix] {

			# Use asynchronous connections.  Very cool.
			if [ catch {socket -async $addr $port} sockFd] {
				statusBar "Error connecting to $addr:$port : $sockFd"
				set needResched 1
			} else {
				# We need to be non-blocking until we're connected.
				fconfigure $sockFd -blocking 0

				# Now wait for it to connect
				lappend waitSocks $sockFd
				fileevent $sockFd writable sockConnected

				keylset servers $idx.fd     $sockFd 
				keylset servers $idx.status OPEN
				Bind_Display
			}

			} else {
			
			# We're on windoze.  Use a blocking connection.  Gross.
			if [ catch {socket $addr $port} sockFd] {
				statusBar "Error connecting to $addr:$port : $sockFd"
				set needResched 1
			} else {
				# We're connected.
				keylset servers $idx.fd     $sockFd
				keylset servers $idx.status CONN

				# Argh.  No select(), so we ALWAYS need to be non-blocking.
				fconfigure $sockFd -blocking 0

				gotConnection $sockFd
			}

			}
		}
	}

	if { $needResched && $resched } {
		tatusBar "Retrying un-established connections in 30 seconds..."
		after 30000 { multiConnectToServer 1 }
	}
}

proc multiDisconnect {} {
	global servers

	foreach idx [keylkeys servers] {
		keylget servers $idx svrInfo
		keylget svrInfo connected connected
		keylget svrInfo fd        fd       

		if $connected { lostConnection $fd }
	}
}

proc sockConnected {} {
	global waitSocks 

	# This line causes windows grief
	set wfds [lindex [select {} $waitSocks {} 0] 1]

	foreach fd $wfds {
		# Delete the event
		fileevent $fd writable {}
		
		# Remove from our wait list
		set idx [lsearch -exact $waitSocks $fd]
		lvarpop waitSocks $idx

		# Make sure we *really* connected
		if [catch { gets $fd } err] {
			lostConnection $fd $err
		} else {
			# Now we want to block
			fconfigure $fd -blocking 1
			gotConnection $fd
		}
	}
}

proc writeClientSock { sockFd data } {

	if [catch {
		flush $sockFd
		puts $sockFd $data
		flush $sockFd
	} err ] {
		statusBar "Error writing to socket: '$err'.\nDisconnecting."
		lostConnection $sockFd
	}
}

proc readMultiSock {} {
	global servers tcl_platform

	set plat $tcl_platform(platform)

	# Figure out which one is readable
	set fds ""
	foreach idx [keylkeys servers] {
		set fd [keylget servers $idx.fd]
		if ![cequal $fd null] {
			lappend fds $fd
		}
	}

	if [cequal $plat unix] {
		set rfds [lindex [select $fds {} {} 0] 0]
	} else {
		# Gross.
		set rfds $fds
	}

	foreach fd $rfds {
		set idx [lsearch $fds $fd]

		if [catch {eof $fd} eof] {
			keylget servers $idx.addr addr
			keylget servers $idx.port port
			statusBar "Error on $addr:$port : $eof"
			lostConnection $fd
			return
		}

		if $eof {
			lostConnection $fd
		} else {
			if [catch {gets $fd} data] {
				keylget conns($fd) addr addr
				keylget conns($fd) port port
				statusBar "Error reading from $addr:$port : $data"
				lostConnection $fd
			} else {
				processServerData $idx $data $fd
			}
		}
	}
}

# end of net code
######################################################################

proc setClientOpts {} {
	global clientOpts adminOpts font

	set f [toplevel .client]

	wm title $f "Client Options"
	wm resizable $f 0 0
	wm group $f .
	wm transient $f .
	grab set $f 

	frame $f.svrs
	label $f.svrs.l -text "Server List: " -width 25 -font $font(bold)
	entry $f.svrs.e -textvariable svrs -width 40 -font $font(norm)
	$f.svrs.e delete 0 end
	$f.svrs.e insert 0 $clientOpts(servers)

	frame $f.sauth
	label $f.sauth.l -text "Auth List: " -width 25 -font $font(bold)
	entry $f.sauth.e -textvariable sauth -width 40 -font $font(norm)
	$f.sauth.e delete 0 end
	$f.sauth.e insert 0 $clientOpts(svrauth)

	frame $f.info
	label $f.info.l -text "Options below require a GUI restart before changes will appear." -font $font(bold)
	
	frame $f.loghist
	label $f.loghist.l -text "Log History: " -width 25 -font $font(bold)
	entry $f.loghist.e -textvariable loghist -width 40 -font $font(norm)
	$f.loghist.e delete 0 end
	$f.loghist.e insert 0 $adminOpts(loghist)

	frame $f.logheight
	label $f.logheight.l -text "Log Height: " -width 25 -font $font(bold)
	entry $f.logheight.e -textvariable logheight -width 40 -font $font(norm)
	$f.logheight.e delete 0 end
	$f.logheight.e insert 0 $adminOpts(logheight)

	frame $f.lbxheight
	label $f.lbxheight.l -text "Table Height: " -width 25 -font $font(bold)
	entry $f.lbxheight.e -textvariable lbxheight -width 40 -font $font(norm)
	$f.lbxheight.e delete 0 end
	$f.lbxheight.e insert 0 $adminOpts(lbxheight)

	frame $f.fontsize
	label $f.fontsize.l -text "Font Size: " -width 25 -font $font(bold)
	entry $f.fontsize.e -textvariable fontsize -width 40 -font $font(norm)
	$f.fontsize.e delete 0 end
	$f.fontsize.e insert 0 $font(size)

	foreach id "svrs sauth info loghist logheight lbxheight fontsize" {
		pack $f.$id.l -side left
		catch { pack $f.$id.e -side left -expand y -fill x }
		pack $f.$id -expand y
	}

	frame $f.buts
	button $f.buts.a -text "Save" -command {

		set clientOpts(servers) [.client.svrs.e get]
		set clientOpts(svrauth) [.client.sauth.e get]

		foreach id "loghist logheight lbxheight" {
			set adminOpts($id) [.client.$id.e get]
		}

		set font(size) $fontsize

		writeConfig
		destroy .client
	}

	button $f.buts.c -text "Cancel" -command {
		destroy .client
	}

	label $f.buts.l -text "" -width 5 -font $font(bold)

	pack $f.buts.a -side left 
	pack $f.buts.l -side left 
	pack $f.buts.c -side right
	pack $f.buts

	centerWindow $f .

	update idletasks
}

proc processServerData { idx data fd } {
	global serverUp authLevel svrInfo userInfo servers

	if [cequal $data ""] return

	if [catch { keylget data type } type] {
		statusBar "Protocol error: $type"
		statusBar "Invalid data from hlds_ld: $data"
		lostConnection $fd
		return
	}

	keylget servers $idx.addr addr
	keylget servers $idx.port port

	keylget data up up
		
	if ![catch {keylget data time} time] {
		set timeleft $time
	} else {
		set timeleft 0
	}

	keylget servers $idx.init gotInit

	if { [cequal $type INIT] } {

		keylget data auth authLevel 

		set name "$addr:$port"
		keylget data name name

		switch -exact -- $authLevel {
			0 { 
				statusBar "You're not authorized on $name!"
				lostConnection $fd
				return
			}

			1 { statusBar "You're authorized as a USER on $name." }

			2 { statusBar "You're authorized as an ADMINISTRATOR on $name." }
			default {
				set err \
				"[now] Unknown authLevel received from $name : $authLevel"
				.alert.text configure -text $err -bg red
				statusBar $err
				lostConnection $fd
				return
			}
		}

		keylset servers $idx.auth $authLevel

		# setAuthState

		set name "$addr:$port"
		if $up {
			keylget data name name
			keylget data ip   ip
			keylget data max  max
			keylget data port port
			set status UP
		} else {
			set status DOWN
		}

		keylset servers $idx.init   1
		keylset servers $idx.status $status
		keylset servers $idx.name   $name

		Bind_Display

	} elseif !$gotInit {
		statusBar "Didn't get INIT message from $addr:$port!"
		lostConnection $fd
		return
	}

	keylset servers $idx.time  [updateTimer $timeleft]

	if !$up {
		keylset servers $idx.status DOWN
		keylset servers $idx.time   ??:??
		keylset servers $idx.users  0
		keylset servers $idx.map    ?????
	}

	keylget servers $idx.name name

	switch -exact -- $type {
		UPDATE {
			foreach id "users pings frags times ips userid wonid" {
				keylget data data.$id $id
			}

			keylget data data.map  map
			keylget data data.cnt  cnt
			keylget data data.vote vote

			keylset servers $idx.users  $cnt
			keylset servers $idx.map    $map

			Bind_Display
			statusBar "Refreshed $name" 0
		}

		TEXT    {}
		SB      {}
		STATUS  {}
		MAPLIST {}

		ERR {
			keylget data data err
			.alert.text configure -text "($name) $err" -bg red
			logText "($name) $err"
		}
	}
}

proc updateTimer { timeleft } {

	if [cequal $timeleft 0] {
		set maprem ??:??
	} elseif ![ctype digit $timeleft] {
		set maprem $timeleft
	} else {
		set maprem ""
		set mapsec $timeleft
		set maphr  [expr $mapsec / 3600]
		if $maphr { set maprem "$maphr:" }

		set mapmin [expr [expr $mapsec / 60] % 60]
		set mapsec [format %02d [expr $mapsec % 60]]

		append maprem $mapmin:$mapsec
	}

	return $maprem
}

proc getIdxFromFd { fd } {
	global servers

	set fds ""
	foreach idx [keylkeys servers] {
		lappend fds [keylget servers $idx.fd]
	}

	set idx [lsearch $fds $fd]

	return $idx
}

proc gotConnection { fd } {
	global servers

	set idx [getIdxFromFd $fd]

	keylget servers $idx.addr addr
	keylget servers $idx.port port

	statusBar "Connected to hlds_ld on $addr:$port..."
	writeClientSock $fd [keylget servers $idx.authstr]
	fileevent $fd readable readMultiSock

	keylset servers $idx.connected 1
	keylset servers $idx.status    CONN

	#.menubar.file.menu entryconfigure 0 -state disabled
	#.menubar.file.menu entryconfigure 1 -state normal

	Bind_Display
}

proc lostConnection { fd {err ""}} {
	global servers

	set idx [getIdxFromFd $fd]

	keylget servers $idx.addr addr
	keylget servers $idx.port port
	keylget servers $idx.init init

	if ![cequal $err ""] {
		statusBar "Unable to connect to $addr:$port: $err"
	} elseif !$init {
		statusBar "You probably entered the wrong authorization for $addr:$port"
	} else {
		statusBar "Closed connection to $addr:$port"
	}

	catch { close $fd }

	initServers $idx

	Bind_Display
}


proc logText { text } {
	global adminOpts

	.info.text configure -state normal
	.info.text insert end "$text\n" 
	set lines [.info.text index end]
	.info.text see end 

	if { $lines > $adminOpts(loghist) } {
		set cnt [expr int($lines) - $adminOpts(loghist)]
		.info.text delete 0.0 $cnt.0
	}
	.info.text configure -state disabled
}

#######################################################################
# tkerror - supress any gui error msgs; server *may* continue to run...?
#
#proc tkerror {errmsg} {
#     puts stderr "An error has occurred.  If you can reliably reproduce it,"
#     puts stderr "please contact the author!   See Help->About."
#     puts stderr $errmsg
#}


######################################################################
# centerWindow - center a window on the display or relative to a 
#                   parent window
#
# Args:
#        window  - window to be centered
#        parent  - (optional) parent window in which 'window'
#                  should be centered. If empty, 'window' is
#                  centered on the display
#
# Notes:
#
# This really only works if the size of the window has already been
# established.  For example, if a window hasn't been mapped yet it's
# width and height may very will be 1x1. Grep for examples of how to
# work around this
#
# PACKAGE-EXPORT centerWindow
#
proc centerWindow {window {parent {}}} {

    set centerDisp 1
    if {$parent != {}} {
	if {[winfo viewable $parent]} {
	    set centerDisp 0
	} 
    } 

    if {$centerDisp} {
	set pw [winfo screenwidth $window]
	set ph [winfo screenheight $window]
    } else {
	set pw [winfo width $parent]
	set ph [winfo height $parent]
    }

    set width [expr [winfo reqwidth $window] + 10]
    set height [expr [winfo reqheight $window] + 10]

    if {$centerDisp} {
	set xo 0
	set yo 0
    } else {
	set xo [winfo x $parent]
	set yo [winfo y $parent]
    }

    set x [expr ($pw / 2) - ($width / 2) + $xo]
    set y [expr ($ph / 2) - ($height / 2) + $yo]

    set screen $parent
    if {$parent == {}} {set screen .}
    set maxX [expr [winfo screenwidth $screen] - $width]
    set maxY [expr [winfo screenheight $screen] - $height]
    set x [min [max $x 0] $maxX]
    set y [min [max $y 0] $maxY]

    wm geometry $window "+$x+$y"
}

proc statusBar { text {log 1} } {
	global adminOpts

	if { $log < 2 } {
		.statusbar configure -text $text
	}

	if $log {
		.info.text configure -state normal
		.info.text insert end "$text\n" 
		set lines [.info.text index end]
		.info.text see end 

		if { $lines > $adminOpts(loghist) } {
			set cnt [expr int($lines) - $adminOpts(loghist)]
			.info.text delete 0.0 $cnt.0
		}
		.info.text configure -state disabled
	}

	update idletasks
}

proc popupListBox { title height list okcmd } {
	global lbcmd font

	set lbcmd $okcmd
	set f [toplevel .listBox]

	wm title $f $title
	wm resizable $f 0 0
	wm group $f .
	wm transient $f .
	grab set $f 

	frame $f.lb
	scrollbar $f.lb.sb -orient vertical -command [list $f.lb.lb yview]

	listbox $f.lb.lb -height $height -yscrollcommand [list $f.lb.sb set] -font $font(norm)
	pack $f.lb.sb -side left -fill y -expand y
	pack $f.lb.lb -side right
	pack $f.lb
	foreach item $list {
		$f.lb.lb insert 0 $item
	}

	frame $f.buts
	button $f.buts.a -text "Apply" -command {
		catch {
		[$lbcmd [.listBox.lb.lb get [.listBox.lb.lb curselection]]]
		}
		destroy .listBox
	} -font $font(norm)

	button $f.buts.c -text "Cancel" -command {
		destroy .listBox
	} -font $font(norm)
	pack $f.buts.a -side left 
	pack $f.buts.c -side right
	pack $f.buts

	centerWindow $f .

	tkwait window $f
}

proc popupError { error } {
	global vers errText font
	set f .error

	set errText $error

	toplevel $f

	wm title $f "$vers Error"
	wm resizable $f 0 0
	wm group $f .
	wm transient $f .
	grab set $f 

	frame $f.f
	message $f.f.t -fg red -bg black -text $errText -justify left 
	pack $f.f.t

	frame $f.buts
	button $f.buts.d -text "Dismiss" -command {destroy .error}
	pack $f.buts.d -side bottom
	button $f.buts.s -text "Save Error Msg" -command {
		set fd [open hlgui.err a]
		puts $fd [replicate = 70]
		puts $fd "Error occurred [now]"
		puts $fd ""
		puts $fd $errText
		puts $fd ""
		close $fd
		.error.sb.l configure -text "Saved msg to [pwd]/hlgui.err"
	}
	pack $f.buts.d -side left
	pack $f.buts.s -side right
	pack $f.buts -side bottom -fill x -expand 1

	frame $f.sb -relief raised -bd 3
	label $f.sb.l -text "" -font $font(bold)
	pack $f.sb.l
	pack $f.sb -side bottom -fill x -expand 1

	pack $f.f

	centerWindow $f .

	update idletasks
	tkwait window $f
}

proc Bind_Display {} {
	global lbxs userInfo adminOpts svrInfo font servers

	# Get the current selection, if any
	set idx [.table.server.l curselection]
	set oldId "xxx"
	if ![cequal $idx ""] {
		set server [.table.server.l get $idx]
		set oldId $server
	}

	# Do the table
	foreach lbx $lbxs {
		$lbx delete 0 end
	}

	set i 0
	set tot 0
	foreach server [keylkeys servers] {
		set name [keylget servers $server.name]
		.table.server.l insert end $name

		foreach id "status users map time" {
			.table.$id.l insert end [keylget servers $server.$id]
		}

		# Put the selection back if that server is still around
		if [cequal "$name" $oldId] {
			foreach id "server status users map time" {
				.table.$id.l selection set $i
			}
		}

		incr tot [keylget servers $server.users]
		incr i
	}

	.stats.tot configure -text "Total Users: $tot"
}

proc BindDragto { x y args } {
        foreach w [lindex $args 0] {
                $w scan dragto $x $y
        }
}

proc BindMark { x y args } {
        foreach w $args {
                $w scan mark $x $y
        }
}

proc BindYview { lists args } {
        foreach l $lists {
                eval {$l yview} $args
        }
}

proc BindSelect { y args } {
        foreach w [lindex $args 0] {
                $w select clear 0 end
                $w select anchor [$w nearest $y]
                $w select set anchor [$w nearest $y]
        }
}

proc writeConfig {} {
	global clientOpts adminOpts gameId kl font cfgFile

	if [catch {open $cfgFile w} fd] {
		popupError "Error opening configuration file: $fd"
		exit 1
	}


	keylset kl CLIENT.loghist   $adminOpts(loghist)
	keylset kl CLIENT.logheight $adminOpts(logheight)
	keylset kl CLIENT.lbxheight $adminOpts(lbxheight)
	keylset kl CLIENT.fontsize  $font(size)

	keylset kl SERVERS $clientOpts(servers)
	keylset kl SVRAUTH $clientOpts(svrauth)

	puts $fd [replicate # 78]
	puts $fd "# hlds_ld Cluster Configuration File"

	if [catch {
		puts $fd "# Updated [now], [id user]"
	} err] {
		puts $fd "# Updated [now]"
	}

	puts $fd [replicate # 78]
	puts $fd "#"
	puts $fd ""
	foreach item $kl {
		puts $fd [list $item]
	}

	close $fd
}

proc readConfig {} {
	global clientOpts adminOpts gameId kl env font cfgFile

	if [info exists env(HLDIR)] {
		cd $env(HLDIR)
	}

	set cfgFile hlds_ld_cluster.cfg

	if ![file exists $cfgFile] {
		popupError "
Can't find '$cfgFile' file!
Please start this GUI from the directory that
contains the $cfgFile file, or
set the environment variable HLDIR to point
to the proper directory."
		exit 1
	}

	if [catch {open $cfgFile r} fd] {
		popupError "Error opening configuration file: $fd"
		exit 1
	}

	set kl ""
	while 1 {
		set line [gets $fd]
		if [eof $fd] break
		if {[cequal [string trim $line] ""] || \
			[cequal [csubstr [string trim $line] 0 1] "#"]} continue
		append kl " $line"
	}

	set adminOpts(lbxheight) 10
	set adminOpts(logheight) 10
	set adminOpts(loghist)   300

	set font(size) 14

	set clientOpts(servers) ""
	set clientOpts(svrauth) ""

	keylget kl CLIENT.loghist   adminOpts(loghist)
	keylget kl CLIENT.logheight adminOpts(logheight)
	keylget kl CLIENT.lbxheight adminOpts(lbxheight)
	keylget kl CLIENT.fontsize  font(size)

	keylget kl SERVERS clientOpts(servers)
	keylget kl SVRAUTH clientOpts(svrauth)
}

proc buildTable {} {
	global lbxs adminOpts font

	set lbxfs [list .table.server .table.status .table.users .table.map \
		.table.time]

	foreach lbxf $lbxfs {
		lappend lbxs ${lbxf}.l
	}
   #
   # Server, status, users, map, Time Left
   #

	frame .table
	set frame .table

	set widths [list 30 8 3 15 7]
	set hdrs [list Server Status Users Map "Time Left"]

	# Five listboxes and a scrollbar
	set i 0
	foreach lbxf $lbxfs {
		frame $lbxf
		if !$i {
			scrollbar $lbxf.sy -orient vertical \
				-command [list BindYview $lbxs]
			set sf $lbxf.sy
		}
		label $lbxf.t -text [lindex $hdrs $i] -font $font(bold)
		set lbx $lbxf.l
			
		set export "false"
		if !$i {set export "true"}
		listbox $lbxf.l \
			-yscrollcommand [list $sf set] \
			-exportselection $export \
			-bg black -fg green \
			-width [lindex $widths $i] \
			-height $adminOpts(lbxheight) \
			-font $font(norm)
		incr i
	}
	pack $sf -side left -fill y


	set i 0
	foreach lbx $lbxfs {
		pack $lbx.t -side top -fill both -expand y
		pack $lbx.l -side bottom -fill both -expand y
		pack $lbx -side left -expand y
		incr i
	}

	foreach lbx $lbxs {
		bind $lbx <ButtonPress> \
			[list BindSelect %y $lbxs]
		bind $lbx <ButtonRelease> \
			[list BindSelect %y $lbxs]
		bind $lbx <Button> \
			[list BindSelect %y $lbxs]
		bind $lbx <B1-Motion> \
			[list BindDragto %x %y $lbxs]
		bind $lbx <B2-Motion> \
			[list BindDragto %x %y $lbxs]
	}

	pack .table -fill x -expand y
}

proc execCmd {{cmd ""}} {
	global servers

	if [cequal $cmd ""] {
		set cmd [.cmd.e get]
		.cmd.e delete 0 end
	}
	if [cequal $cmd ""] return

	set idx [getCurrentSelection]

	if { $idx < 0 } return

	keylget servers $idx.fd        fd
	keylget servers $idx.connected connected
	keylget servers $idx.status    status
	keylget servers $idx.name      name
	keylget servers $idx.auth      auth

	if !$connected {
		statusBar "You're not connected to that server!" 0
		sleep 1
		return
	}

	if { $auth < 2 } {
		statusBar "You're not authorized to control that server!" 0
		sleep 1
		return
	}

	if ![cequal $status UP] {
		statusBar "Server isn't up!"
		sleep 1
		return
	}

	statusBar "Sent '$cmd' to '$name'..."

	writeClientSock $fd $cmd
}

proc now {} {
	return [clock format [clock seconds]]
}

proc setFont { } {
	global font

	set size $font(size)
	set font(bold) "-*-helvetica-bold-r-normal-*-$font(size)-*-*-*-*-*-*-*"
	set font(norm) "-*-helvetica-medium-r-normal-*-$font(size)-*-*-*-*-*-*-*"
}

proc makeMenuBar {} {
	global font
   # 
   # Menubar
   # 
   menubutton .menubar.file -text "File" -menu .menubar.file.menu -font $font(bold)
   pack .menubar.file -side left
   menu .menubar.file.menu -tearoff 0
   .menubar.file.menu add command -label "Connect All" -command { multiConnectToServer } -font $font(bold)
   .menubar.file.menu add command -label "Disconnect All" -command { multiDisconnect } -font $font(bold)
   .menubar.file.menu add separator
   .menubar.file.menu add command -label "Exit" -command {destroy .} -font $font(bold)

   menubutton .menubar.options -text "Options" -menu .menubar.options.menu \
	-font $font(bold)
   pack .menubar.options -side left
   menu .menubar.options.menu -tearoff 0
   .menubar.options.menu add command -label "Client Options" \
	-command setClientOpts -font $font(bold)
   .menubar.options.menu add command -label "Reset Alert" \
	-command {
		.alert.text configure -text "<No Alerts>" -bg green
	} -font $font(bold)

   menubutton .menubar.help -text "Help" -menu .menubar.help.menu -font $font(bold)

   pack .menubar.help -side right
   menu .menubar.help.menu -tearoff 0
   .menubar.help.menu add command -label "About" -command aboutGui -font $font(bold)
   .menubar.help.menu add separator
   .menubar.help.menu add command -label "Menu Bar" -command menuHelp -font $font(bold)
   .menubar.help.menu add command -label "Buttons" -command buttonHelp -font $font(bold)
   .menubar.help.menu add separator
   .menubar.help.menu add command -label "Conditions" -command cdm -font $font(bold)
   .menubar.help.menu add command -label "Warranty" -command warranty -font $font(bold)

   pack .menubar -side top -fill x -expand true
}


proc initServers {{idx -1}} {
	global servers clientOpts

	proc subInitServers { idx } {
		global servers clientOpts

		keylset servers $idx.status    DISCON
		keylset servers $idx.users     0
		keylset servers $idx.map       ?????
		keylset servers $idx.time      ??:??
		keylset servers $idx.init      0
		keylset servers $idx.auth      0
		keylset servers $idx.authstr   [lindex $clientOpts(svrauth) $idx]
		keylset servers $idx.connected 0
		keylset servers $idx.fd        null
	}

	if { $idx < 0 } {
		set idx 0
		foreach server $clientOpts(servers) {
			set split [split $server :]
			set addr [lindex $split 0]
			set port [lindex $split 1]

			keylset servers $idx.name $server
			keylset servers $idx.addr $addr
			keylset servers $idx.port $port

			subInitServers $idx
			incr idx
		}
	} else {
		subInitServers $idx
	}

	Bind_Display
}

proc getCurrentSelection {} {
	set idx [.table.server.l curselection]
	if [cequal $idx ""] {
		statusBar "Please select a server..." 0
		sleep 1
		return -1
	}

	return $idx
}

proc launchHLgui {} {
	global servers env tcl_platform

	set idx [getCurrentSelection]

	if { $idx < 0 } return

	keylget servers $idx.name    name
	keylget servers $idx.addr    addr
	keylget servers $idx.port    port
	keylget servers $idx.authstr authstr

	set plat $tcl_platform(platform)

	set junk [replicate . 80]
	set gotErr 0

	set myauthstr $authstr
	if [cequal $authstr ""] { set myauthstr {} }

	if [cequal $plat unix] {
		if [catch {system "hlgui $port $addr $junk $myauthstr &" } err] { set gotErr 1 }
	} elseif [cequal $plat windows] {
		if [catch {exec wishx ./hlgui $port $addr $junk $myauthstr & } err] { set gotErr 1 }
	} else {
		# Whoa.  Mac or something else.  Punt :)
		if [catch {exec wish ./hlgui $port $addr $junk $myauthstr & } err] { set gotErr 1 }
	}

	if $gotErr {
		popupError "
Unable to launch hlgui.   The error was:

$err

Please check Help->About and make sure you have things set up
correctly.
"
	}
}

proc stopStartSvr {} {
	global servers

	set idx [getCurrentSelection]

	if { $idx < 0 } return

	keylget servers $idx.fd        fd
	keylget servers $idx.connected connected
	keylget servers $idx.status    status
	keylget servers $idx.name      name
	keylget servers $idx.auth      auth


	if !$connected {
		statusBar "You're not connected to that server!" 0
		sleep 1
		return
	}

	if { $auth < 2 } {
		statusBar "You're not authorized to control that server!" 0
		sleep 1
		return
	}

	if [cequal $status UP] {
		statusBar "Stopping $name..."
		writeClientSock $fd quit
	} elseif [cequal $status DOWN] {
		statusBar "Starting $name..."
		writeClientSock $fd START
	} else {
		statusBar "Server is neither UP or DOWN, try again later..."
	}
}

proc hlDebug { msg } {
	global debugFlag

	if $debugFlag {
		set fd [open hlgui.debug a]
		puts $fd $msg
		close $fd
	}
}

proc refreshServers {} {
	global servers

	foreach idx [keylkeys servers] {
		keylget servers $idx.fd        fd
		keylget servers $idx.connected connected
		keylget servers $idx.status    status
		keylget servers $idx.name      name
		keylget servers $idx.auth      auth

		if !$connected { continue }
		if { $auth < 2 } { continue }
		if ![cequal $status UP] { continue }
		
		writeClientSock $fd REFRESH
	}
}

proc usage {} {
	popupError "
Usage: hlclustermon \[port \[addr\]\]

Where: 

port = The TCP port to use to connect to hlds_ld.  This will override the port set in your configuration file.

addr = The IP address to use to connect to hlds_ld.  This will override the port set in your configuration file.
"
	exit 1
}

#######################################################################
# MAIN - the main gui program.
#
proc main { argc argv } {
   global lbxs adminOpts clientOpts gameId env fds vers sockFd authString font

   frame .menubar -relief raised -borderwidth 3
   
   readConfig
   setFont

	if { $argc < 3 && $argc > 0 } {
		lassign $argv port addr
		if ![ctype digit $port] { usage }
		# Only arg is port
		set clientOpts(port) $port
		if ![cequal $addr ""] { set clientOpts(addr) $addr }
	} elseif { $argc > 0 } {
		usage
	}

	makeMenuBar

	# Alert frame
	frame .alert
	label .alert.text -text "<No Alerts>" -bg green  -font $font(bold) \
		-anchor center
	pack .alert.text -side left -fill x -expand true
	pack .alert -fill x

	# Statistics
	frame .stats
	label .stats.tot -text "Total Users: 0" -font $font(bold)
	pack .stats.tot -side left -expand y
	pack .stats -fill x -expand y

	buildTable

	# Buttons
	frame .buts
	set t .buts
	button $t.stopstart -text "Start / Stop Server" -command stopStartSvr \
		-font $font(norm)
	button $t.hlgui -text "Launch hlgui" -command launchHLgui \
		-font $font(norm)
	button $t.refresh -text "Refresh" -command refreshServers \
		-font $font(norm)

	pack $t.stopstart $t.hlgui $t.refresh -side left \
		-fill x -expand y
	pack $t -fill x

	# Command entry
	frame .cmd
	label .cmd.l -text "Server Command: " -width 17 -font $font(bold)
	entry .cmd.e -font $font(norm)
	pack .cmd.l -side left
	pack .cmd.e -side left -fill x -expand y
	pack .cmd -fill x
	bind .cmd.e <Return> execCmd

	# Statusbar
	label .statusbar -relief raised -text "[now] Welcome to hlclustermon!" \
		-font $font(bold) -anchor center -bd 3
	pack .statusbar -side top -fill x -expand y

	# Logging area
	frame .info
	text .info.text -height $adminOpts(logheight) -state normal \
		-yscroll ".info.sy set" -font $font(norm)
	scrollbar .info.sy -command ".info.text yview" -width 15
	.info.text insert end "[now] Welcome to hlclustermon!\n"
	.info.text configure -state disabled
	pack .info.sy -side left -fill y
	pack .info.text -side right -expand y -fill x
	#pack .info -expand y -fill both
	pack .info -fill both

	#serverDown

	# Resize foo
	#	wm resizable . 0 1
	#	grid .t  -sticky ns
	#	grid rowconfigure .t 0 -weight 2 -minsize 3
	#	grid rowconfigure . 0 -weight 1 
		wm resizable . 0 0

	wm title . $vers

	logText "See Help->About for licensing and copyright details."

	initServers
}

proc bgerror { error } {
    global errorCode errorInfo font

	popupError "
An error occurred.  If you can reliably reproduce this, please send the
error to linuxhlds@halflife.org, along with a description of the steps
you took to reproduce the issue.  Thanks!

($errorCode) : $errorInfo
"
}

proc checkForExtendedTcl {} {
	if { [string length [info commands cequal]] > 0 } { return }

	puts stderr "The Tk interpeter you are running is NOT an Extended Tk"
	puts stderr "(TkX) interpreter."
	puts stderr "hlgui requires TkX.  Please install TkX and try again."

	exit 1
}

#######################################################################
# set some variables for use in the procs and call MAIN
#
checkForExtendedTcl

set lastMap ""
set font(size) 12
setFont

set svrInfo(name)    ""
set svrInfo(logFile) ""
set svrInfo(reconnect) 0
set svrInfo(kills) 0
set svrInfo(max) 0
set svrInfo(timeleft) 0
set svrInfo(player) 0
set svrInfo(vote) 0

set vers "hlclustermon $vnum"
set notIdle 1

set gettingText 0

# Close the Tk security hole
if [cequal [info commands send] send] {
	catch { rename send {} }
}
# tk appname hlgui ;# Debug only!

set debugFlag 0

#set dfd [open dbg w]
#cmdtrace on $dfd

set vnum 1.50b2

main [llength $argv] $argv
