#!/bin/bash
#
# This IRC script won't run under some versions of bash, but I think
# it's a super job of programming.  I will try to find the author and
# credit him appropriately.
#

if [ $# -lt 4 ]; then
	echo "Usage: $0 server port nick channel";
	exit;
fi

exec 5<>/dev/tcp/$1/$2
register=0;

while [ 1 ]; do
	read line <&5
	echo $line;
	if [ $register -eq 0 ]; then
		register=1;
		sleep 3;
		echo "here"
		echo "USER bash linespeed.net $1 :$3" >&5
		sleep 1;
		echo "NICK $3" >&5
	fi

	if echo "$line" | grep " 376 " ; then
		echo "JOIN #$4" >&5
		break;

	else
		data=`echo $line | cut -d' ' -f4-`;
		echo $data		
	fi
done

while [ 1 ]; do
	if read -t 1 line <&5 ; then
		if echo "$line" | grep -i "PING :" ; then
			server=`echo $line | cut -d: -f2`;
			echo "PONG :$server" >&5
		elif echo "$line" | grep -i "PRIVMSG" ; then
			echo $line;
		fi			
		
	fi

	if read -t 1 input <&0 ; then
		echo "PRIVMSG #$4 :$input" >&5
	fi
done

exec 5>&-

