import Data.Char
import Data.List
import Network
import System.IO
import System.Environment
import Text.Printf

main = do
    [nick, chan, socket] <- getArgs
    h <- connectTo "" $ UnixSocket socket
    hSetBuffering h NoBuffering
    write h "NICK" nick
    write h "USER" (nick++" 0 * :"++nick)
    write h "JOIN" chan
    reader h nick chan

write :: Handle -> String -> String -> IO ()
write h s t = do
    hPrintf h "%s %s\r\r" s t
    printf    "> %s %s\n" s t

reader :: Handle -> String -> String -> IO ()
reader h nick chan = forever $ do
    t <- hGetLine h
    let s = init t
    eval h (clean s) nick chan
    putStrLn s
  where
    forever a = do a; forever a
    clean     = drop 1 . dropWhile (/= ':') . drop 1

eval :: Handle -> String -> String -> String -> IO ()
eval h x nick chan
    | ping x           = pong x
    | isInfixOf nick x = say ((map toUpper nick) ++ " RULES")
    | otherwise        = return()
  where
    ping x    = isPrefixOf "PING :" x
    pong x    = write h "PONG" (':' : drop 6 x)
    say  s    = write h "PRIVMSG" (chan ++ " :" ++ s)
