#!/usr/bin/env pythonw
import os
import plistlib
import MacOS

try:
    # Python23Compat
    from LaunchServices import LaunchServices, Launch
except ImportError:
    # Python 2.4
    from Carbon import LaunchServices, Launch

def executableForIdentifier(spec):
    # CFStings are unicode, if we're going to have a problem with this
    # then have it now..
    if not isinstance(spec, unicode):
        spec = unicode(spec, 'utf8')
    def attempts():
        kUnk = LaunchServices.kLSUnknownCreator
        # try the given spec as a CFBundleIdentifier
        yield kUnk, spec, None
        # try it as the application name
        yield kUnk, None, spec
        # try it as the creator code
        if len(spec) == 4:
            yield spec.encode('macroman'), None, None
        # try it as the application name again with .app
        yield kUnk, None, spec + '.app'
        # try it as a python string escaped creator code
        try:
            creator = spec.encode('macroman').decode('string_escape')
        except ValueError:
            pass
        else:
            if len(creator) == 4:
                yield creator, None, None
    for attempt in attempts():
        try:
            myRef, myURL = Launch.LSFindApplicationForInfo(*attempt)
            break
        except MacOS.Error:
            pass
    else:
        return None
    myPath = myRef.as_pathname()
    plist = plistlib.Plist.fromFile(os.path.join(myPath, 'Contents', 'Info.plist'))
    return os.path.join(myPath, 'Contents', 'MacOS', plist['CFBundleExecutable'])

if __name__ == '__main__':
    import sys
    import codecs
    sys.stdout = codecs.getwriter('utf8')(sys.stdout)
    error = 0
    for spec in sys.argv[1:]:
        res = executableForIdentifier(spec.decode('utf8'))
        if res is None:
            print spec + u': Command not found.'
            error = 1
        else:
            print res
    raise SystemExit(error)