#!/usr/bin/wish

set maildir "~/Maildir"
wm title . "xgaspode"
wm geometry . =+40+40

proc checkMailLoop { } {
	checkMail
	after 5000 checkMailLoop
}

proc checkMail { } {
	global maildir
	set count 0
	catch {
		set count [ exec bash -c "find $maildir -mindepth 2 -maxdepth 2 \\\( -path '*/new/*' -o -regex '.*/cur/.*,\[^SD\]*' \\\) | grep -c ." ]
	}
	.unread configure -text $count
 	if { $count > 0 } {
		.unread configure -background "green"
	} else {
		.unread configure -background "gray"
	}
	if { $count == 1 } {
		wm title .headersPopup "1 unread message in Inbox"
	} else {
		wm title .headersPopup "$count unread messages in Inbox"
	}
	catch {
                set count [ exec bash -c "find $maildir -mindepth 2 -maxdepth 2 \\\( -path '*/new/*' -o -regex '.*/cur/.**,\[^D\]*' \\\) | grep -c ." ]
        }
	.total configure -text "of\n$count"
}

proc getHeaders { } {
	global maildir
	set headers "No messages"
	catch {
		set headers [ exec bash -c "find $maildir -mindepth 2 -maxdepth 2 \\\( -path '*/new/*' -o -regex '.*/cur/.**,\[^SD\]*' \\\) -exec bash -c \"cat {} | grep -m 1 ^From: ; cat {} | grep -m 1 ^Subject: \" ';'" ]
	}
	if { $headers == "" } { set headers "No messages" }
	.headersPopup.label configure -text $headers
}

toplevel .headersPopup
wm title .headersPopup "Unread Messages in Inbox"
label .unread -text "?" -font [ font create -size 40 -family "Helvetica" ]
label .total -text "of\n"
label .headersPopup.label -text "Unknown" -justify "left" 

bind . <ButtonPress-3> exit
bind . <ButtonPress-1> { exec evolution & }
bind . <Enter> {
	checkMail
	getHeaders
	set x [ winfo pointerx . ]
	incr x 10
	set y [ winfo pointery . ]
	wm geometry .headersPopup =+$x+$y
	wm deiconify .headersPopup
}
bind . <Leave> { 
	wm withdraw .headersPopup 
}

pack .unread .total .headersPopup.label -side "left"
wm withdraw .headersPopup
wm transient .headersPopup .
checkMailLoop
