#!/bin/bash -e
# spot is a simple doge.
# spot thanks github.com/Newbrict/bash-irc-bot for the regexes

echo "NICK spot-woof" > spot.input
echo "USER spot-woof 0 biscuit :Spot The Doge" >> spot.input
echo "JOIN #spot" >> spot.input
echo "PRIVMSG Nickserv :identify <password>" >> spot.input

tail -f spot.input | telnet irc.freenode.net 6667 | while read; do
	echo $(date +%s): "$REPLY" >> spot.log
	case "$REPLY" in
		*PING)
			echo "PONG $(echo $REPLY | awk '{print $2}')" >> spot.input # spot likes ping-pong
		;;
		*PRIVMSG*)
			echo "$REPLY"
			HUMAN=$(echo "$REPLY" | perl -pe "s/:(.*)\!.*@.*/\1/")
			METHOD=$(echo "$REPLY" | perl -pe "s/.*PRIVMSG (.*[#]?([a-zA-Z]|\-)*) :.*/\1/")
			MSG=$(echo "$REPLY" | perl -pe "s/.*$nick :(.*)/\1/")
			if [[ $(echo "$METHOD" | grep "#") ]]; then
				if [[ $(echo "$MSG" | grep '^!') ]]; then
					COMMAND=$(echo "$MSG" | awk '{print $1}')
					if [[ "$COMMAND" == '!tip' ]]; then
						RECIPIENT=$(echo "$MSG" | awk '{print $2}')
						AMOUNT=$(echo "$MSG" | awk '{print $3}')
						if [[ -z "$RECIPIENT" ]] || [[ -z "$AMOUNT" ]]; then
							echo PRIVMSG "$METHOD" :"$HUMAN" made a mistake with his syntax! Bad doge! Should be \"!tip <user> <amount>\" >> spot.input
						else
							echo PRIVMSG "$METHOD" :"$HUMAN" tips "$RECIPIENT" "$AMOUNT" dogecoin! >> spot.input
						fi
					fi
				fi
			else
				echo PRIVMSG "$HUMAN" ":Hey there! Let me process that command of yours!" >> spot.input
				COMMAND=$(echo "$MSG" | awk '{print $1}')
				case "$COMMAND" in
					help)
						echo PRIVMSG "$HUMAN" ":Spot is a simple doge." >> spot.input
						echo PRIVMSG "$HUMAN" ":He knows how to trade dogecoin though." >> spot.input
						echo PRIVMSG "$HUMAN" ":Tip someone by saying \"!tip <user> <amount>\" in a channel that spot is in." >> spot.input
						echo PRIVMSG "$HUMAN" ":There are no fees, and there will never be any fees. Really, you can hold me to that." >> spot.input
						echo PRIVMSG "$HUMAN" ":Well, except for the 1 doge withdrawal fee. Don't blame spot; blame the system." >> spot.input
						echo PRIVMSG "$HUMAN" ":Spot was created from scratch by Harry Prevor, AKA 'habs' on freenode." >> spot.input
						echo PRIVMSG "$HUMAN" ":You can give him the D too: DPMkiwht5TTbtvUVAKj1hbXUku7NZMz8jj" >> spot.input
					;;
					withdraw)
						ADDRESS=$(echo "$MSG" | awk '{print $2}')
						if [[ -z "$ADDRESS" ]]; then
							echo PRIVMSG "$HUMAN" ":You made a mistake with your syntax! Bad doge! Should be \"withdraw <address>\"" >> spot.input
						else
							dogecoind
						fi
					;;
				esac
			fi
		;;
	esac
done
