#!/usr/bin/env python3
"""Seed a fresh Chrome user-data-dir with a cookies content-setting exception
of the shape that triggers the bug:

    primary  = *                (wildcard, GetHost() == "")
    secondary = [*.]example.test  (domain wildcard, GetHost() == "example.test")
    setting  = BLOCK (2)

Because primary.GetHost() is empty and secondary.GetHost() is "example.test",
HostIndexedContentSettings::SetValue() files this rule under
secondary_host_indexed_["example.test"].

Usage: python3 seed-prefs.py /tmp/chrome-poc-profile
"""
import json
import os
import sys

CONTENT_SETTING_BLOCK = 2

PREFS = {
    "profile": {
        "content_settings": {
            "exceptions": {
                "cookies": {
                    "*,[*.]example.test": {"setting": CONTENT_SETTING_BLOCK}
                }
            },
            "pref_version": 1,
        },
        # Disable third-party-cookie blocking heuristics so the explicit rule
        # is the only thing that should block the IP-literal cookie.
        "cookie_controls_mode": 0,
    }
}


def main():
    if len(sys.argv) != 2:
        print(f'usage: {sys.argv[0]} <user-data-dir>', file=sys.stderr)
        sys.exit(1)
    udd = sys.argv[1]
    default = os.path.join(udd, 'Default')
    os.makedirs(default, exist_ok=True)
    with open(os.path.join(default, 'Preferences'), 'w') as f:
        json.dump(PREFS, f)
    # Mark first-run complete so Chrome doesn't clobber the profile.
    with open(os.path.join(udd, 'First Run'), 'w') as f:
        pass
    print(f'Seeded {default}/Preferences with rule (*,[*.]example.test)=BLOCK')


if __name__ == '__main__':
    main()
