#!/usr/local/bin/python
version = "0.0.3"
#####################################################################
# rox-add-app
#
# Converted during build from the .py to an executable script.
# The local python path is inserted (e.g. "#!/usr/bin/python") in
# order to make it self-running and to have the proper process name.
#####################################################################

'''Add to the rox "menu" (~/Apps) by creating an AppDir'''

import sys
import os
import os.path

scriptName = os.path.split(sys.argv[0])[1]

baseDir = os.path.expanduser('~/Apps')

######################################################################
if __name__ == '__main__':
######################################################################
    if len(sys.argv) < 3:
        print '''
Usage: %s <submenu> <command> <name>
''' % scriptName
        sys.exit(1)

    submenu = sys.argv[1]
    command = sys.argv[2]
    if len(sys.argv) > 3:
        name = sys.argv[3]
    else:
        name = os.path.split(command)[1]
        f = os.popen('Xdialog --stdout --input "Select icon caption:" 10 40 "%s"' % name)
        for s in f.readlines():
            name = s.strip()
            break
        f.close()

    submenuDir = os.path.join(baseDir, submenu)
    if os.path.exists(submenuDir):
        if not os.path.isdir(submenuDir):
            print 'ERROR: Submenu path "%s" already exists, and is not a directory' % submenuDir
            sys.exit(1)
    else:
        print 'Creating submenu directory "%s"...' % submenuDir
        os.makedirs(submenuDir)

    appDir = os.path.join(submenuDir, name)
    if os.path.exists(appDir):
        if not os.path.isdir(appDir):
            print 'ERROR: App dir path "%s" already exists, and is not a directory' % appDir
            sys.exit(1)
    else:
        print 'Creating app dir "%s"...' % appDir
        os.makedirs(appDir)

    print 'Populating app dir "%s"...' % appDir 
    appRun = os.path.join(appDir, 'AppRun')
    fapp = open(appRun, 'w')
    fapp.write('''
#!/bin/sh
%s $@''' % command)
    fapp.close()
    os.chmod(appRun, 0775)
