# copyright (C) 1997-2006 Jean-Luc Fontaine (mailto:jfontain@free.fr)
# this program is free software: please read the COPYRIGHT file enclosed in this package or use the Help Copyright menu

# $Id: myvars.tcl,v 1.61 2006/03/16 21:29:56 jfontain Exp $


package provide myvars [lindex {$Revision: 1.61 $} 1]
if {![catch {package require Thread 2.5}]} {           ;# use threads so that core is not blocked on connection problems with server
    package require stooop 4.1
    namespace import stooop::*
    package require threads 1
    namespace eval myvars {
        variable thread
        set thread(busy) 0
        set thread(worker) [new worker]
    }
}


namespace eval myvars {}
source myvars.dat

namespace eval myvars {

    array set data {
        updates 0
        0,label {} 0,type ascii 0,message {} 0,0 {}
        pollTimes {60 10 20 30 60 120 300}
        persistent 0
        switches {--dsn 1 --host 1 --password 1 --port 1 --user 1}
    }
    set file [open myvars.htm]
    set data(helpText) [read $file]                                                           ;# initialize HTML help data from file
    close $file
    if {[info exists thread]} {                     ;# show on last line of this module help window that we are running with threads
        regsub -nocase </body> $data(helpText) "<p><i>(currently running in threaded mode)</i>\n\\0" data(helpText)
    }

    proc initialize {optionsName} {
        upvar 1 $optionsName options
        variable thread
        variable odbc
        variable connection
        variable data
        variable help
        variable type
        variable nameColumn

        set user $::tcl_platform(user)                                                                                 ;# by default
        catch {set user $options(--user)}
        if {[info exists options(--dsn)]} {                                               ;# ODBC mode id data source name specified
            set odbc 1
            package require tclodbc 2                               ;# so that it works with both UNIX 2.2.1 et Windows 2.3 versions
            if {[info exists options(--host)] || [info exists options(--port)]} {
                error {--host and --port options incompatible with ODBC mode}
            }
            set arguments [list $options(--dsn)]
            catch {lappend arguments $user}
            catch {lappend arguments $options(--password)}
            if {[info exists thread]} {
                worker::evaluate $thread(worker) {package require tclodbc 2}
                set connection [worker::wait $thread(worker) "database odbc $arguments"]             ;# use a unique connection name
                set list [worker::evaluate $thread(worker) "$connection {show variables like 'version'}"]
            } else {
                package require tclodbc 2                           ;# so that it works with both UNIX 2.2.1 et Windows 2.3 versions
                set connection [eval database odbc $arguments]                                       ;# use a unique connection name
                set list [$connection {show variables like 'version'}]
            }
            set data(identifier) myvars($options(--dsn))
            scan [lindex [lindex $list 0] 1] %u.%u.%u major minor subMinor
        } else {
            set odbc 0
            package require mysqltcl
            if {[info exists options(--port)] && (![info exists options(--host)] || [string equal $options(--host) localhost])} {
                error {--port option useless with local socket connection (localhost as host)}
            }
            set arguments {}
            catch {lappend arguments -host $options(--host)}
            catch {lappend arguments -user $user}
            catch {lappend arguments -password $options(--password)}
            catch {lappend arguments -port $options(--port)}
            if {[info exists thread]} {
                worker::evaluate $thread(worker) {package require mysqltcl}
                set connection [worker::wait $thread(worker) "mysqlconnect $arguments"]                           ;# do not hang GUI
                set host [worker::evaluate $thread(worker) "lindex \[mysqlinfo $connection host\] 0"]
                # do not retrieve version in background as it is unlikely to fail if connection was established:
                set list [worker::evaluate $thread(worker) "mysqlsel $connection {show variables like 'version'} -flatlist"]
            } else {
                package require mysqltcl
                set connection [eval mysqlconnect $arguments]
                set host [lindex [mysqlinfo $connection host] 0]           ;# work around mysqltcl 3 return value: "host via TCP/IP"
                set list [mysqlsel $connection {show variables like 'version'} -flatlist]
            }
            set data(identifier) myvars($host)
            scan [lindex $list 1] %u.%u.%u major minor subMinor
        }
        switch $major {
            3 {
                if {$minor != 23} {error "cannot monitor a server version 3.$minor"}
                if {$subMinor < 57} {error {cannot monitor a server below version 3.23.57 in the 3.23 series}}
            }
            4 - 5 {
                if {$minor > 1} {error "cannot monitor a server version $major.$minor"}
            }
            default {
                error "cannot monitor a server version $major"
            }
        }
        if {$odbc} {
            if {[info exists thread]} {
                worker::evaluate $thread(worker)\
                    "$connection statement $connection.query {show variables}; $connection.query execute"
            } else {
                $connection statement $connection.query {show variables}; $connection.query execute
            }
        } else {
            if {[info exists thread]} {
                worker::evaluate $thread(worker) "mysqlsel $connection {show variables}"
            } else {
                mysqlsel $connection {show variables}
            }
        }
        set variables {}
        while {1} {                                                                     ;# gather existing variables from the server
            if {$odbc} {
                if {[info exists thread]} {
                    set list [worker::evaluate $thread(worker) "$connection.query fetch"]
                } else {
                    set list [$connection.query fetch]
                }
            } else {
                if {[info exists thread]} {
                    set list [worker::evaluate $thread(worker) "mysqlnext $connection"]
                } else {
                    set list [mysqlnext $connection]
                }
            }
            if {[llength $list] == 0} break
            set variable [lindex $list 0]
            lappend variables $variable
            # look for some global options so that whole groups of variables can be skipped to reduce displayed table height:
            switch $variable {
                have_bdb {
                    if {![string equal -nocase [lindex $list end] yes]} {
                        set skip(bdb) {}
                    }
                }
                have_innodb {
                    if {![string equal -nocase [lindex $list end] yes]} {
                        set skip(innodb) {}
                    }
                }
                have_isam {
                    if {![string equal -nocase [lindex $list end] yes]} {
                        set skip(myisam) {}
                    }
                }
            }
        }
        set columns {}
        set column 0
        foreach variable $variables {
            if {[info exists nameColumn($variable)]} continue      ;# happens with 4.1.8 where innodb_max_purge_lag is listed twice!
            incr column              ;# keep column numbers even for non displayed columns in case those get enabled at a later time
            if {[info exists skip([lindex [split $variable _] 0])]} continue                                        ;# not displayed
            set nameColumn($variable) $column                                                            ;# remember variable column
            set data($column,label) $variable
            set data($column,type) real                                                                                ;# by default
            catch {set data($column,type) $type($variable)}
            if {![info exists help($variable)]} {
                puts stderr "\"$variable\" variable is not recognized by myvars: please contact author."
                set data($column,message) {not recognized: please contact author}
            } elseif {[string length $help($variable)] == 0} {
                set data($column,message) {undocumented in the MySQL documentation}
            } else {
                set data($column,message) $help($variable)
            }
            set data($column,anchor) left
            lappend columns $column
        }
        if {$odbc} {
            if {[info exists thread]} {
                worker::evaluate $thread(worker) "$connection.query drop"
            } else {
                $connection.query drop
            }
        }
        unset help type                                                                                          ;# save some memory
        set data(views) [list [list indices $columns swap 1]]
    }

    proc update {} {
        variable thread

        if {[info exists thread]} {
            if {$thread(busy)} return
            set thread(busy) 1
        }
        getVariables
    }

    proc getVariables {{result {}} {errorInformation {}}} {
        variable thread
        variable odbc
        variable connection
        variable data
        variable nameColumn

        set error 0
        if {[info exists thread]} {
            if {[string length $result] == 0} {                                                        ;# launch query in background
                if {$odbc} {
                    worker::evaluate $thread(worker)\
                        "$connection statement $connection.query {show variables}; $connection.query execute; list 1"\
                        myvars::getVariables
                } else {
                    worker::evaluate $thread(worker) "mysqlsel $connection {show variables}; list 1" myvars::getVariables
                }
                return                                       ;# this procedure is invoked back with a non-empty result (1) when done
            } elseif {[string length $errorInformation] > 0} {                                                   ;# an error occured
                set error 1
                set message $result
            }                                                                           ;# else the query was executed with no error
        } else {
            if {$odbc} {
                set error [catch {$connection statement $connection.query {show variables}; $connection.query execute} message]
            } else {
                set error [catch {mysqlsel $connection {show variables}} message]
            }
        }
        if {$error} {                                                                                     ;# problem reaching server
            flashMessage "error: $message"
            foreach {name column} [array get nameColumn] {
                switch $data($column,type) {
                    integer - real {set data(0,$column) ?}
                    default {set data(0,$column) {}}
                }
            }
        } else {
            while {1} {
                if {[info exists thread]} {
                    # no need for background work since the whole data is already in this client (mysql_store_result() used):
                    if {$odbc} {
                        set list [worker::evaluate $thread(worker) "$connection.query fetch"]
                    } else {
                        set list [worker::evaluate $thread(worker) "mysqlnext $connection"]
                    }
                } else {
                    if {$odbc} {
                        set list [$connection.query fetch]
                    } else {
                        set list [mysqlnext $connection]
                    }
                }
                if {[llength $list] == 0} break
                foreach {variable value} $list {}
                if {[catch {set column $nameColumn($variable)}]} continue         ;# column has been filtered out (see initialize{})
                set data(0,$column) $value
            }
        }
        if {$odbc} {
            # ignore connection errors at this point (they will be reported at next poll):
            if {[info exists thread]} {
                catch {worker::evaluate $thread(worker) "$connection.query drop"}
            } else {
                catch {$connection.query drop}
            }
        }
        if {[info exists thread]} {
            set thread(busy) 0
        }
        incr data(updates)
    }

    proc terminate {} {
        variable thread
        variable odbc
        variable connection

        if {![info exists connection]} return                                        ;# connection may have failed in initialization
        if {$odbc} {
            if {[info exists thread]} {
                worker::evaluate $thread(worker) "$connection disconnect" list            ;# try to disconnect while ignoring errors
                delete $thread(worker)
            } else {
                catch {$connection disconnect}
            }
        } else {
            if {[info exists thread]} {
                worker::evaluate $thread(worker) "mysqlclose $connection" list      ;# try to close connection while ignoring errors
                delete $thread(worker)
            } else {
                catch {mysqlclose $connection}
            }
        }
    }

}
