#!/bin/sh
server=irc.underworld.no
port=6667
nickname=ksh93
channel='#df.lth.se'
set -m
cd

irc() {
	if ! pgrep ii; then
		ii -s "$server" -p "$port" -n "$nickname" 2>&1 >irclogs &
	fi
}

join() {
	if pgrep ii; then
		echo "/j $channel" > "irc/$server/in"
	fi
}

readline() {
	tail -f "irc/$server/$channel/out" |while read -r timestamp username message; do
		response=
		command=
		case $message in
			'>'*)
				command=${message#>}
				if syntax=$(sh -nc "$command" 2>&1); then
					response=$(sh -c "$command" | head -n 2)
					test -n "$response" && printf %s\\n "$response" > "irc/$server/$channel/in" && continue
				else
					continue
				fi
				;;
			*) continue
		esac
	done 
}

irc
sleep 5
join
sleep 5

readline
