#!/usr/bin/python
"""Install an extension proxy into a Firefox profile pointing here.

This is based on the method described on the Mozilla developer wiki:

https://developer.mozilla.org/en/setting_up_extension_development_environment

This provides an alternative to building and installing XPIs during
development.
"""

import os
import ConfigParser
import sys
from xml.etree import cElementTree as ET


profiles_ini = os.path.join(
    os.environ['HOME'], '.mozilla', 'firefox', 'profiles.ini')


def get_profile_dirs(profiles_ini):
    """Get a map of Firefox profile names to profile directories."""
    cp = ConfigParser.ConfigParser()
    cp.read(profiles_ini)
    profiles = {}
    for section in cp.sections():
        if not section.startswith('Profile'):
            continue
        name = cp.get(section, 'name')
        path = cp.get(section, 'path')
        if cp.getboolean(section, 'isrelative'):
            path = os.path.join(os.path.dirname(profiles_ini), path)
        profiles[name] = path
    return profiles


def get_extension_id(install_rdf):
    """Get the extension ID from a Firefox extension install.rdf file."""
    # This isn't doing proper RDF processing, but should work for most
    # extension RDF files.
    tree = ET.parse(install_rdf)
    id_node = tree.find(
        '{http://www.w3.org/1999/02/22-rdf-syntax-ns#}Description/'
        '{http://www.mozilla.org/2004/em-rdf#}id')
    assert id_node is not None, "Could not find extension ID"
    return id_node.text


def install_extension_proxy(extension_dir, profile_dir):
    """Install an extension proxy file to a Firefox profile."""
    extension_dir = os.path.realpath(extension_dir)
    extension_id = get_extension_id(
        os.path.join(extension_dir, 'install.rdf'))
    proxy_file = os.path.join(profile_dir, 'extensions', extension_id)
    if os.path.exists(proxy_file):
        os.remove(proxy_file)
    fp = open(proxy_file, "wb")
    fp.write(extension_dir)
    fp.close()
    # Make sure the new extension is reloaded on next startup.
    for file in ['extensions.cache', 'extensions.ini', 'extensions.rdf']:
        path = os.path.join(profile_dir, file)
        if os.path.exists(path):
            os.remove(path)


def main(argv):
    """Install the extension into a named profile."""
    if len(argv) < 2:
        sys.stderr.write('usage: %s PROFILE\n' % argv[0])
        return 1
    profile_name = argv[1]
    profiles = get_profile_dirs(profiles_ini)
    if profile_name not in profiles:
        sys.stderr.write('Unknown profile %s\n' % profile_name)
    install_extension_proxy('.', profiles[profile_name])


if __name__ == '__main__':
    sys.exit(main(sys.argv))

