# Small plugin, that puts an output from a command into status.
# Useful (for example) to people using xmms2, that want to put
# their current song into status

namespace eval shstatus {
}

proc shstatus::load {} {
    custom::defgroup ShStatus \
	[::msgcat::mc "Options for module that automatically sets your status to some command's output."] \
	-group Tkabbur

    custom::defvar options(shstatuson) false \
	[::msgcat::mc "Turn on ShStatus."] \
	-group ShStatus -type boolean

    custom::defvar options(shstatuscmd) \
	[::msgcat::mc ""] \
	[::msgcat::mc "Command to be executed every second and put its output into user status."] \
	-group ShStatus -type string

    hook::add connected_hook    [namespace current]::after_idle
    hook::add disconnected_hook [namespace current]::after_idle_cancel
}

proc shstatus::after_idle {args} {
    after cancel [namespace current]::after_idle
    after_idle_aux
    after 1000 [namespace current]::after_idle
}
proc shstatus::after_idle_cancel {args} {
    if {[jlib::connections] == {}} {
	after cancel [namespace current]::after_idle
    }
}
proc shstatus::execa {cmd} {
	set res [catch {set output [eval exec $cmd]} errMsg]
	if {$res} {
	    set msg $errMsg
	} else {
	    set msg $output
	}
	return $msg
}
proc shstatus::after_idle_aux {} {
    variable options
    global textstatus userstatus
    if {!$options(shstatuson)} {
        return
    }
	
    set msg [[namespace current]::execa $options(shstatuscmd)]
    debugmsg iq $msg
    if {$msg!=$textstatus} {
	set textstatus $msg
	set userstatus $userstatus
    }
}

shstatus::load

