#!/usr/bin/env python3
"""
Creates a fresh Chrome user-data-dir with geolocation + notifications
pre-granted to http://localhost:8080. This simulates the realistic precondition
where the victim has previously granted geolocation to the legitimate
(non-sandboxed) parts of victim.com.

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

if len(sys.argv) != 2:
    print("Usage: python3 setup_profile.py <profile-dir>", file=sys.stderr)
    sys.exit(1)

profile_dir = sys.argv[1]
default_dir = os.path.join(profile_dir, "Default")

# Clean and recreate.
if os.path.exists(profile_dir):
    shutil.rmtree(profile_dir)
os.makedirs(default_dir)

# Pre-grant geolocation + notifications to http://localhost:8080.
# Geolocation uses TOP_ORIGIN_ONLY_SCOPE -> pattern is "<origin>,*".
# setting:1 == CONTENT_SETTING_ALLOW.
# No expiration / session_model:0 (DURABLE) -> persists across runs.
prefs = {
    "profile": {
        "content_settings": {
            "exceptions": {
                "geolocation": {
                    "http://localhost:8080,*": {"setting": 1}
                },
                "notifications": {
                    "http://localhost:8080,*": {"setting": 1}
                },
            }
        }
    }
}

with open(os.path.join(default_dir, "Preferences"), "w") as f:
    json.dump(prefs, f)

print(f"Profile created at {profile_dir}")
print(f"  geolocation:   GRANTED for http://localhost:8080")
print(f"  notifications: GRANTED for http://localhost:8080")
