#!/usr/bin/env python3
"""
Developers should subscribe to:
  https://codeberg.org/librewolf/settings/rss/branch/master/distribution/policies.json
"""
import email, json, os
from urllib.request import urlopen, urlretrieve

git = []

## Firefox policies

url = 'https://codeberg.org/librewolf/settings/raw/branch/master/distribution/policies.json'
target = 'etc/firefox/policies/policies.json'
extensions = (
  'uBlock0@raymondhill.net',
  'keepassxc-browser@keepassxc.org',
  'jid1-tfBgelm3d4bLkQ@jetpack', # Copy as Markdown
)

with urlopen(url) as x:
  root = json.load(x)

policies = root['policies']
for x in list(policies):
  if x.startswith('Disable'):
    if x[7:] in ('FirefoxStudies', 'Pocket', 'Telemetry'):
      continue
  elif x not in ('AppUpdateURL', 'NoDefaultBookmarks', 'SupportMenu',
                  'WebsiteFilter'):
    continue
  del policies[x]
x = extensions
z = policies['ExtensionSettings'][x[0]]
url = z.pop('install_url').replace('/%s/' % x[0], '/%s/')
policies['ExtensionSettings'] = {x: dict(z, install_url=url % x) for x in x}
policies['HttpsOnlyMode'] = 'enabled'

with open(target, 'w') as x:
  json.dump(root, x, indent=2, sort_keys=True)
git.append(target)

## OBS repository

with open('etc/apt/sources.list.d/obs-vifibnexedi.sources') as x:
  x = email.message_from_file(x)
git.append(x['Signed-By'][1:])
urlretrieve(x['URIs'] + '/Release.key', git[-1])

os.execlp('git', 'git', 'add', *git)
