#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# v0.1 by Charles Barcza kbarcza at blackpanther.hu [www.blackpanther.hu]
# szimszon scriptje utan..

import dbus, gobject, dbus.glib, re, os, sys, time, getopt


#text=text.encode("utf-8","replace") If you system encode different used
ENC = 'iso8859-2'
bus = dbus.SessionBus()

def run_pidgin():
	os.system("echo Pidgin IM starting....")
	os.system("pidgin &")
	os.system("sleep 5")
	os.system("echo Pidgin OSD started....")
	obj = bus.get_object(
			"im.pidgin.purple.PurpleService", "/im/pidgin/purple/PurpleObject")
	pidgin = dbus.Interface(obj, "im.pidgin.purple.PurpleInterface")
	buddy_data_cache = {}

def command_line():

	try:
		opts, args = getopt.getopt(sys.argv[1:], "c:f:s:ph", ["command",\
			"file","signal","pipe","help"])
	except getopt.GetoptError:
		usage()
		sys.exit(2)
	hash={}
	hash["command"]="/usr/bin/osd_cat -s 1 -S black --font=-*-helvetica-medium-r-*-*-*-220-*-*-*-*-*-"
	#hash["command"]="/usr/bin/osd_cat -s 1 -S black --font=-*-helvetica-medium-r-*-*-*-320-*-*-*-*-*-"
	#optionals parameters  --color=blue --age=4 --font=-*-helvetica-medium-r-*-*-*-320-*-*-*-*-*-* --offset=100 --align=right --indent=100 (osd options)
	hash["file"]="/tmp/pidgin_osd.tmp"
	hash["signal"]="ReceivedImMsg"
	hash["pipe"]=True
	return hash

def onReceivedImMsg(junk,bId,txt,junk2,junk3):
	re_body=re.compile("<[^>*]>")
	re_br=re.compile("<[Bb][Rr]/?>")
	text=txt
	text = re_br.sub("\n",text)
	text = re_br.sub(" ",text)
	text=text.encode(ENC,"replace")
	if command_line()["pipe"]:
		#os.system("echo -e \'"+str(text)+"\' | awk -F'0\">'  '{print $2}' | awk -F'</' '{print $1}'|cat > /tmp/msg")
		os.system("echo -e \'"+str(text)+"\' | awk -F'0\">'  '{print $2}' | awk -F'</' '{print $1}'|"+str(command_line()["command"]))
		#os.system("echo -e \'"+str(text)+"\'")
	else:
	 f=open(command_line()["file"],"w")
	 f.write(text+"\n")
	 f.close()
	 #os.system("echo -e \'"+str(text)+"\' | awk -F'0\">'  '{print $2}' | awk -F'</' '{print $5}' | cat > /tmp/msg")
	 os.system("echo -e \'"+str(text)+"\' | awk -F'0\">'  '{print $2}' | awk -F'</' '{print $1}'| "+str(command_line()["file"]))
	 #os.system(str(command_line()["command"])+" "+str(command_line()["file"]))
	 os.unlink(str(command_line()["file"]))
	time.sleep(1)

bus.add_signal_receiver(onReceivedImMsg,
	dbus_interface="im.pidgin.purple.PurpleInterface",
	signal_name="ReceivedImMsg")


run_pidgin()

command_line()
gobject.MainLoop().run()
