#!/usr/bin/python
#
# fillprofile    Fill in full paths for files in Platypus profile
#
import os
import sys
from xml.etree.ElementTree import ElementTree
from xml.etree.ElementTree import XMLParser
from xml.etree.ElementTree import TreeBuilder

platypus_profile = 'psilauncher.platypus'

def lookup(tree, k):
    "return value associated with key in plist, or None if not present"
    it = tree.iter()
    for e in it:
        if e.tag == 'key' and e.text == k:
            try:
                return it.next()
            except:
                break
    return None

def newdir(d, e):
    "replace directory part of string element's text; d has trailing slash"
    if e is not None and e.tag == 'string':
        slix = e.text.rfind('/')
        if slix < 0:
            e.text = d + e.text
        else:
            e.text = d + e.text[slix + 1 :]

def newdirs(d, e):
    "replace directory part of strings in array element; d has trailing slash"
    if e is not None and e.tag == 'array':
        for child in e:
            newdir(d, child)


class MyTb(TreeBuilder):
    doctypestrs = []
    def __init__(self, sar):
        TreeBuilder.__init__(self)
        self.doctypestrs = sar
    def doctype(self, name, pubid, system):
        self.doctypestrs[0] = name
        self.doctypestrs[1] = pubid
        self.doctypestrs[2] = system


def fillprofile(p):
    "set full paths of files in platypus profile"
    slix = p.rfind('/')
    if slix >= 0:
        d = p[0 : slix + 1]
        tree = ElementTree()
        dtstrs = ['', '', '']
        tree.parse(p, XMLParser(0, MyTb(dtstrs)))
        newdir(d, lookup(tree, 'IconPath'))
        newdir(d, lookup(tree, 'ScriptPath'))
        newdirs(d, lookup(tree, 'BundledFiles'))
        file = open(p, "w")
        file.write('<?xml version="1.0" encoding="UTF-8"?>\n');
        file.write('<!DOCTYPE ' + dtstrs[0] + ' PUBLIC "' + dtstrs[1] + \
                    '" "' + dtstrs[2] + '">\n')
        tree.write(file, 'UTF-8', False)
        file.write('\n')
        file.close()


def main():
    "find Platypus profile and modify in place"
    dir = os.getcwd()
    while True:
        p = dir
        if p[-1] != '/':
            p = p + '/'
        p = p + platypus_profile
        if os.path.isfile(p):
            fillprofile(p)
            exit(0)
        if dir == '/':
            sys.stderr.write('fillprofile: ' + platypus_profile + ' not found\n')
            exit(1)
        slix = dir.rfind('/')
        if slix <= 0:
            dir = '/'
        else:
            dir = dir[0 : slix]


main()
