#!/usr/bin/env python3
"""Write exactly one desktop color policy for the supported browsers."""
# Policy approach adapted from Omarchy's omarchy-theme-set-browser-policy (MIT, Basecamp).
# https://github.com/basecamp/omarchy/blob/master/bin/omarchy-theme-set-browser-policy
import json
import os
import re
import sys
import tempfile
from pathlib import Path

# Ungoogled Chromium's sandbox exposes its documented Policy extension, not the host's /etc.
# https://github.com/flathub/io.github.ungoogled_software.ungoogled_chromium#extension-points
POLICY_DIRS = ('/etc/chromium/policies/managed', '/etc/brave/policies/managed',
               '/var/lib/flatpak/extension/io.github.ungoogled_software.ungoogled_chromium.Policy.starchaser/x86_64/1/policies/managed')
# Only ancestors inside these public app trees may have their permissions repaired.
POLICY_ROOTS = ('/etc/chromium', '/etc/brave', '/var/lib/flatpak')
PREFERENCE = '/etc/brave/starchaser-tint.json'


def policy(color):
    if not re.fullmatch(r'[0-9a-f]{6}', color):
        raise ValueError('Choose one color as six lowercase hex digits.')
    return {'BrowserThemeColor': '#' + color}


def protected_directory(directory, create=True):
    # Fixed root-owned paths only. Refuse symlinks in every parent, including policy trust roots.
    path = Path(directory)
    for parent in reversed((path, *path.parents)):
        if parent.is_symlink():
            raise OSError('A browser policy folder is a link.')
        if not parent.exists() and not create:
            continue
        if create:
            parent.mkdir(exist_ok=True)
        if parent.stat().st_uid != 0 or parent.stat().st_mode & 0o022:
            raise OSError("A browser policy folder isn't protected.")
        # pkexec preserves a private caller umask. Repair old 0700 folders too,
        # after checking ownership and protection; leave /etc and /var/lib alone.
        if create and any(parent.is_relative_to(root) for root in POLICY_ROOTS):
            parent.chmod(0o755)
    return path


def remove(file):
    path = Path(file)
    protected_directory(path.parent, create=False)
    # Unlink the fixed entry itself; never follow a file symlink.
    path.unlink(missing_ok=True)


def save(directory, payload, filename='starchaser-color.json'):
    path = protected_directory(directory)
    fd, tmp = tempfile.mkstemp(prefix='.starchaser-color.', dir=path)
    try:
        with os.fdopen(fd, 'w') as out:
            json.dump(payload, out)
            out.write('\n')
            out.flush()
            os.fsync(out.fileno())
            os.fchmod(out.fileno(), 0o644)
        os.replace(tmp, path / filename)
    finally:
        if os.path.exists(tmp):
            os.unlink(tmp)


def main(args):
    if args in (['--help'], ['-h']):
        print('Usage: starchaser-browser-theme <rrggbb|off>\nTurn browser tint on with a color, or remove it for everyone.')
        return 0
    try:
        if len(args) != 1:
            raise ValueError('Expected one color.')
        payload = None if args[0] == 'off' else policy(args[0])
    except ValueError as error:
        print(f'{error}\nUsage: starchaser-browser-theme <rrggbb|off>', file=sys.stderr)
        return 2
    if os.geteuid() != 0:
        print('Run the installed browser color helper through pkexec.', file=sys.stderr)
        return 1
    try:
        for directory in POLICY_DIRS:
            if payload is None:
                remove(Path(directory) / 'starchaser-color.json')
            else:
                save(directory, payload)
        if payload is None:
            remove(PREFERENCE)
        else:
            save(Path(PREFERENCE).parent, {'enabled': True}, Path(PREFERENCE).name)
    except OSError as error:
        print(f'The browser color could not be saved: {error}', file=sys.stderr)
        return 1
    return 0


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