#!/usr/bin/env python

# 
# Utility script for
# anyRemote - a bluetooth remote for your PC.
#
# Copyright (C) 2007,2008 Mikhail Fedotov <anyremote@mail.ru>
# 
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 
# 

import os
import re
import sys
import threading

class AllInOne:
    def __init__(self, dirToParse):
        
	self.rdr = CfgFileReader(dirToParse+os.sep+'Server-mode');
	self.rdr.run()

class CfgFileReader(threading.Thread):

    def __init__(self, cfgDir):
	threading.Thread.__init__(self) 
	self.cfgDir  = cfgDir      

    def run(self):

    	cfg = os.environ.get("HOME")+os.sep+'.anyRemote'+os.sep+'AllInOneTmp.cfg'
 	f=open(cfg, 'w')
	if f:
 	    f.write('[Keys]\n')
 	    f.write('[Mode]=_ALL_IN_ONE_\n')

	    self.regExpIcon  = re.compile("^[^a-zA-Z0-9]*GuiAppIcon")
	    self.regExpExec  = re.compile("^[^a-zA-Z0-9]*GuiAppBinary")
	    self.regExpAll1  = re.compile(".*ALLIN1MENU.*")

	    fillCMD='FILL_LIST=Set(iconlist,replace,Applications';
	    
	    try:
	         files = os.listdir(self.cfgDir)
	    except OSError:
	         print "Error: directory not exists "+self.cfgDir
		 f.close()
		 return
		 
	    files.sort()
	    i = 0;
	    iconsList = []
	    
	    for cfgFile in files:
	        icon = self.processOneFile(self.cfgDir + os.sep + cfgFile)

		if icon != []: 

		    fillCMD = fillCMD+','+icon[0]+':'+icon[1]
			
		    if icon[0] not in iconsList:
		
		        i2 = i + 1

		        f.write('UPLOAD'+str(i)+'=Get(is_exists,16,'+icon[0]+');\n')
		        f.write('IconNotExists('+icon[0]+')=Set(text,replace,SAME,uploading '+icon[0]+'\\n);ExecAndSet(image,icon,echo \'F=`find /usr/share/icons -name '+icon[0]+'.png|grep 16|head -1`;if [ "x$F" == "x" ]; then F=`find /usr/share/pixmaps -name "'+icon[0]+'.*"|head -1`;F2=/tmp/'+icon[0]+'.png;cat $F|convert - -resize 16x16 -depth 8 $F2; F=$F2; fi;echo "'+icon[0]+',$F"\'|bash -f -s);Macro(UPLOAD'+str(i2)+');\n')
		        f.write('IconExists('+icon[0]+')=Set(text,replace,SAME,'+icon[0]+' OK);Macro(UPLOAD'+str(i2)+');\n')
		
		        i = i2
			
		        iconsList.append(icon[0])
		    
	    f.write('UPLOAD'+str(i)+'=Macro(FILL_LIST);\n')   

	    f.write('[ModeEnd]\n')    
	    f.write(fillCMD+');Set(menu,replace,Select,Regenerate);\n')    
	    f.write('[End]\n')    
	    f.close()
	    
    def processOneFile(self,cfgFile):
	
	ret = []
	fd = open(cfgFile,'r') 
	n = os.path.basename(cfgFile)
	n = n[:len(n)-4]
	
	if fd and n != '' and n != 'all-in-one':
	    i = None
	    a = None
	    e = None
	    
            for line in fd:
		if i == None and self.regExpIcon.match(line):
	    	    p = re.search("^[^a-zA-Z0-9]*GuiAppIcon[^=]*=(.+)\.(.+)$", line)
	    	    if p != None:
	    		i = p.group(1)

		if e == None and self.regExpExec.match(line):
	    	    x = re.search("^[^a-zA-Z0-9]*GuiAppBinary[^=]*=(.+)$", line)
	    	    if x != None:
	    		e = x.group(1)
			
		if a == None and self.regExpAll1.match(line):
		    a = 1
		
		if a == 1 and i != None and e != None:
		    break
	
	    ex = 1
	    if e != None:
	        which = os.popen('which '+e+' 2> /dev/null').readlines()
		if which == []:
		    #print 'Skip ',e
		    ex = 0
	
	    if a == 1 and i != None and ex == 1:
	        ret = [i,n]   
	
	if fd:
	    fd.close()
	    
	return ret

def main():
    a = AllInOne(sys.argv[1])

    return 0

if __name__ == "__main__":
    main()
