#!/bin/bash
 # BIRC(B) - BASH IRC (Bot)
 # Simple IRC Bot/Client written in BASH
 # <--Harvie 2oo7

 # You can use it as bot or client if anything else can't be installed.
 # In fact, this is a nc/telnet/socket frontend to act as IRC client.
 # Maybe there will be BASH socket (/dev/tcp/...) module in future == no netcat.
 # Other questions -> !!!-UTFS-FM-OMG-!!!
 # Deps: 
	# BASH>=3
	# one of these: (netcat|telnet|socket) - see settings section

#SETTINGS
 BIRCHOST=irc.2600.net
 BIRCPORT=6667
 BIRCNICK=bircbot
 BIRCCHAN=\#bircb
 BIRCWAIT=2
 BIRCSOCK=~/.bircbsock
 NETCAT=nc


#FUNCTIONS
 birc_parse() {
	#PING/PONG
        if [[ "$1" =~ ^PING\ *:\(.*\) ]]; then
                echo "PONG :${BASH_REMATCH[1]}" >> $2
        fi;

	# -> MORE BOT-FUNCTIONS HERE <-
	# BASH is cool, you can just call another script with bot functions from here
 }


 birc_connect() {
	rm -f $1; touch $1;
	rm -f "$1"r; touch "$1"r;

	tail -f $1 | $NETCAT $2 $3 >> "$1"r &

	# while tail -f "$1"r | read BIRCLINE; do
	tail -f "$1"r | while read BIRCLINE; do
		echo "$BIRCLINE"
		birc_parse "$BIRCLINE" $1
	done;
 }

 birc_login() {
	echo NICK "$2" >> $1
	echo USER "$2 $2 $2 :$2" >> $1
	echo >> $1
 }

 birc_join() {
	echo JOIN "$2" >> $1
 }

 birc_say() {
	# -> MORE USER-FUNCTIONS HERE <-

	if [[ "$2" =~ ^/\(.*\) ]]; then
		#Server command
                echo "${BASH_REMATCH[1]}" >> $1
        else
		#Common message
		echo PRIVMSG "$3" :"$2" >> $1
	fi;
 }

 birc_cleanup() {
	echo [!] Quiting BIRC...
	kill -2 $(jobs -p); > /dev/null 2>&1
	kill -9 $(jobs -p); > /dev/null 2>&1
	echo [!] All jobs gone!
	rm -f $1; touch $1; > /dev/null 2>&1
        rm -f "$1"r; touch "$1"r; > /dev/null 2>&1
	echo [!] Temp files removed!
	exit;
 }

#MAIN_C0DE
 echo [*] Starting BASH IRC(Bot)
	trap "birc_cleanup" SIGINT;

 echo [i] Using socket Files/FIFOs "$BIRCSOCK"\(r\)
	birc_connect $BIRCSOCK $BIRCHOST $BIRCPORT &
		sleep $BIRCWAIT;

 echo [i] $USER@$(hostname) -\> $BIRCNICK@$BIRCCHAN@$BIRCHOST:$BIRCPORT
	birc_login $BIRCSOCK $BIRCNICK;
		sleep 1;

 echo [i] Joining channel $BIRCCHAN
	birc_join $BIRCSOCK $BIRCCHAN;

 echo [\>] Now waiting for your messages on STDIN
	while true; do
		read BIRCMESG;
		birc_say $BIRCSOCK "$BIRCMESG" $BIRCCHAN;
	done;

 birc_cleanup;
