#!/bin/bash

if [ "`whoami`" != "chat" ]; then
    echo "you must run this script as the chat user"
    exit
fi

umask 002
cd /usr/local/chatmailparser

while [ 1 == 1 ]; do
    echo "waiting for incoming mail"
    while [ $(stat -c%s "/var/mail/chat") == 0 ]; do
	sleep 1
    done

    echo "mailbox file size changed, checking"

    if [ -e "/tmp/chatmailparser" ]; then
	rm -rf /tmp/chatmailparser
    fi
    mkdir /tmp/chatmailparser

    formail -s sh -c 'cat - > /tmp/chatmailparser/$FILENO.txt' < /var/mail/chat

    for fullfilename in `ls -1 /tmp/chatmailparser/*.txt`; do
	filename=`basename $fullfilename`
	fid=${filename/.txt/}
	if [ ! -e "/tmp/chatmailparser/$fid" ]; then
	    mkdir "/tmp/chatmailparser/$fid"
	fi

	echo "parsing $filename"

	from=`cat $fullfilename | grep -m 1 '^From: '`
	from=${from/From: /}
	if [ -z "$from" ]; then
	    from=`cat $fullfilename | grep -m 1 '^From '`
	    from=${from/From /}
	fi
	from=`./qdecode "$from"`
	subject=`cat $fullfilename | grep -m 1 '^Subject: ' `
	subject=${subject/Subject: /}
	subject=`./qdecode "$subject"`

	echo "extracting attachments"
	./extractattachments "/tmp/chatmailparser/$fid" "$fullfilename"

	echo "processing attachments"
	attachments=""
	for attachment in `ls -1 /tmp/chatmailparser/$fid`; do
	    if [ -z "`echo $attachment | egrep '(\.jpg|\.png|\.gif|\.bmp|\.tiff)\$'`" ]; then
		continue
	    fi

	    destfilename=$attachment
	    attachmentextension=`echo "$attachment" | cut -d'.' -f2`
	    while [ -e "/ftp/chatuploads/$destfilename" ]; do
		destfilename="${destfilename/.$attachmentextension/}_.$attachmentextension"
	    done

	    mv "/tmp/chatmailparser/$fid/$attachment" "/ftp/chatuploads/$destfilename"

	    if [ ! -z "$attachments" ]; then
		attachments="$attachments "
	    fi
	    attachments="${attachments}http://u.nonoo.hu/$attachment"
	done

	if [ -z "$subject" ] && [ -z "$attachments" ]; then
	    echo "no subject or attachment found, ignoring message"
	    continue
	fi

	if [ ! -z "$subject" ]; then
	    subject=" - $subject"
	fi

	if [ ! -z "$attachments" ]; then
	    text="Email érkezett: $from$subject: $attachments"
	else
	    text="Email érkezett: $from$subject"
	fi

	echo "running sql query"
	mysql -u "chat" -p"mysqlpass" -D "chat" -e "INSERT INTO \`chat\`.\`ajax_chat_messages\` ( \`userID\`, \`userName\`, \`userRole\`, \`channel\`, \`dateTime\`, \`text\` ) VALUES ( '75345475647', 'chat.nonoo.hu', 4, 0, NOW(), '$text' );"
    done

    echo -n "" > /var/mail/chat
    rm -rf /tmp/chatmailparser
done
