#!/usr/bin/env python3


import os
import sys
import configparser
import urllib.request
import json


FIREFOX_PATH  = os.path.expanduser('~/.mozilla/firefox')
PROFILES_PATH = os.path.join(FIREFOX_PATH, 'profiles.ini')
API_BASE_URL  = 'https://services.addons.mozilla.org/api/v4/addons/addon'


extension = sys.argv[1]


profiles = configparser.ConfigParser()
profiles.optionxform = str
profiles.read(PROFILES_PATH)
for section in profiles.sections():
    if section.startswith('Profile'):
        profile = dict(profiles.items(section))
        if int(profile['Default']):
            profile_path = profile['Path']
            if int(profile.get('IsRelative', '0')):
                profile_path = os.path.join(FIREFOX_PATH, profile_path)


with urllib.request.urlopen(f'{API_BASE_URL}/{extension}') as response:
    info = json.loads(response.read())
guid = info['guid']
url = info['current_version']['files'][0]['url']
path = os.path.join(profile_path, 'extensions', f'{guid}.xpi')
os.makedirs(os.path.dirname(path), exist_ok=True)
if not os.path.exists(path):
    urllib.request.urlretrieve(url, path)
    print(extension)
