#!/usr/bin/env python

# 
# Utility script for
# anyRemote - a bluetooth remote for your PC.
#
# Copyright (C) 2007-2013 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('[Protocol]=Server\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(".*ALL_IN_ONE.*")

	    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+');Macro(REGEN_MENU);\n')    
	    f.write('[End]\n')    
	    f.close()
	    
    def processOneFile(self,cfgFile):
	
	ret = []
	if not os.path.isfile(cfgFile):
	    return 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:
                cnt = e.count(' ')
                
                if cnt > 0: # treat this like a command to execute
                    e = getResult(e, 'util')
	        
	    	isInst = isInstalled(e)

		if isInst == "NOK":
		    #print 'Skip ',e
		    ex = 0
	
	    if a == 1 and i != None and ex == 1:
	        ret = [i,n]   
	
	if fd:
	    fd.close()
	    
	return ret

def isInstalled(app):
    dirs = os.getenv('PATH').split(':')
    for d in dirs:
        if os.path.exists(d+os.sep+app):
            return 'OK'
    return 'NOK'

def getResult(cmd, suffix):
	
    toFile = os.environ.get("HOME") + os.sep + '.anyRemote' + os.sep + 'anyremote-' + suffix + '.tmp'
    
    os.system(cmd + '> ' + toFile)
    line = getLineTmpFile(toFile)
    return line.replace('\n','')

def getLineTmpFile(toFile):
    fd = open(toFile,'r')
    ln = ''
    if fd:
    	ln=fd.readline()
    	fd.close()
    return ln

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

    return 0

if __name__ == "__main__":
    main()
