#!/usr/bin/env tclsh8.6
#
# plumb.tcl: plumb to the plan9 plumber
#
# To install in the default directory:
#
#	# make install
#
# To install on a different prefix (i.e. your homedir)
#
#	$PREFIX=${HOME} make install
#
# The extension takes data from the selection in a text widget in IRCTk
# and run the plumb executable. The system will decide what to do with
# it.
#

#
# uuid package from Tcllib:
#
# https://core.tcl-lang.org/tcllib
#
package require uuid

set name "Plumb"
set version 1.0.0
set protoversion 1.0

proc newid {} {
	uuid::uuid generate
}

#
# Commands for various message formats as mandated by the IRCTk
# protocol specification:
#
#	https://lab.abiscuola.org/irctk/doc/trunk/www/wiki/extensions.wiki
#

proc handshake {} {
	puts [encoding convertto utf-8 [format "%s\thandshake\t1.0\t%s\t%s\r" \
	    [::newid] $::name $::version]]
}

proc ack {id {msg "ok"}} {
	puts [encoding convertto utf-8 [format "%s\tack\t%s\r" $id $msg]]
}

proc nack {id {msg "ko"}} {
	puts [encoding convertto utf-8 [format "%s\tnack\t%s\r" $id $msg]]
}

proc filter {type} {
	puts [encoding convertto utf-8 [format "%s\tfilter\t%s\r" \
	    [::newid] $type]]
}


while {[gets stdin line] >= 0} {
	#
	# Remember that the messages are exchanged as UTF-8
	#
	set msg [split [encoding convertfrom utf-8 $line] "\t"]

	switch -exact -- [lindex $msg 1] {
		handshake {
			set id [lindex $msg 0]
			#
			# Run the handshake. The protocol is retro-compatible,
			# so we check if the version in our extension is too new
			# for the version of IRCTk we are running.
			#
			if {[lindex $msg 2] < $::protoversion} {
				nack $id "$::name: Incompatible protocol version"

				exit 1
			} else {
				ack $id

				handshake

				filter plumb

				flush stdout
			}
		} nack {
			#
			# Log the reason why we were refused a request
			#
			puts stderr "[lindex $msg 2]"

			flush stderr
		} plumb {
			#
			# Send the data to the system plumber
			#
			if {[catch {exec plumb [format %s [lindex $msg 5]]} errstr]} {
				puts stderr "irctk plumb: $errstr"
			}
		}
	}
}
