#!/usr/bin/env tclsh8.6
#
# search.tcl: search through the IRCTk irc logs
#
# Commands:
#
# SEARCH regexp
#	Search for log lines of a channel, matching the given
#	regular expression
#
# To install in the default directory:
#
#	# make install
#
# To install on a different prefix (i.e. your homedir)
#
#	$PREFIX=${HOME} make install
#
# As an example, to search all the records for 2023/08/29, type
# in a messagebox:
#
#	//search ^2023-08-29
#

source $::env(IRCTK_TCL_SDK)

set name "Search"
set version 1.0.0
set logpath $::env(IRCTK_LOGS_PATH)

proc search {msg} {
	set network [dict get $msg network]
	set channel [dict get $msg channel]
	set search [lindex [dict get $msg args] 0]

	#
	# Open the log channel file
	#
	if {[catch {set fd [open "$::logpath/$network/$channel"]} errstr]} {
		::irctk::ircsend $network $channel-search-error \
		    PRIVMSG $errstr

		return
	}

	#
	# Test if the regexp is ok. If not, report an
	# error for it.
	#
	if {[catch {regexp $search "abcde"} errstr]} {
		::irctk::ircsend $network $channel-search-error \
		    PRIVMSG $errstr
	} else {
		#
		# Grep through the logs and send the lines that
		# matches.
		#
		while {[gets $fd entry] >= 0} {
			if {![regexp $search $entry]} {continue}

			::irctk::ircsend $network $channel-search \
			    PRIVMSG $entry
		}
	}

	close $fd
}

::irctk::init $name $version {}

::irctk::filter irc
::irctk::filter search search

::irctk::loop
