#!/usr/bin/python3
import os
import glob
import pwd

BG_PATH = "/usr/share/backgrounds/cosmic/09-opensuse-4k-geo-cyan.png"

# Collect all possible connector names
connectors = {
    "all",
    "Virtual-1", "Virtual-2",
    "eDP-1", "eDP-2",
    "HDMI-A-1", "HDMI-A-2",
    "DP-1", "DP-2", "DP-3",
    "DVI-I-1", "DVI-D-1"
}
for p in glob.glob("/sys/class/drm/card*-*"):
    base = os.path.basename(p)
    parts = base.split("-", 1)
    if len(parts) == 2:
        connectors.add(parts[1])

entries = []
for c in sorted(connectors):
    entries.append(f'    ("{c}", Path("{BG_PATH}")),')
content = "[\n" + "\n".join(entries) + "\n]\n"

def ensure_user_wallpaper(home_dir, uid, gid):
    state_dir = os.path.join(home_dir, ".local/state/cosmic/com.system76.CosmicBackground/v1")
    wallpapers_file = os.path.join(state_dir, "wallpapers")
    if not os.path.exists(wallpapers_file):
        os.makedirs(state_dir, exist_ok=True)
        with open(wallpapers_file, "w") as f:
            f.write(content)
        for root, dirs, files in os.walk(os.path.join(home_dir, ".local")):
            try:
                os.chown(root, uid, gid)
            except OSError:
                pass
            for f in files:
                try:
                    os.chown(os.path.join(root, f), uid, gid)
                except OSError:
                    pass
    else:
        try:
            with open(wallpapers_file, "r") as f:
                existing = f.read()
            needed = []
            for p in glob.glob("/sys/class/drm/card*-*/status"):
                try:
                    if open(p).read().strip() == "connected":
                        conn = os.path.basename(os.path.dirname(p)).split("-", 1)[1]
                        if f'"{conn}"' not in existing:
                            needed.append(conn)
                except Exception:
                    pass
            if needed:
                closing_idx = existing.rfind("]")
                if closing_idx != -1:
                    new_entries = "\n".join([f'    ("{c}", Path("{BG_PATH}")),' for c in needed])
                    updated = existing[:closing_idx] + new_entries + "\n]\n"
                    with open(wallpapers_file, "w") as f:
                        f.write(updated)
        except Exception:
            pass

def ensure_user_theme_and_shell(home_dir, uid, gid):
    # 1. Enforce openSUSE Chameleon green (#73ba25) accent and Frosted Glass theme
    cosmic_cfg = os.path.join(home_dir, ".config/cosmic")
    dark_b1 = os.path.join(cosmic_cfg, "com.system76.CosmicTheme.Dark.Builder/v1")
    dark_b2 = os.path.join(cosmic_cfg, "com.system76.CosmicTheme.Dark.Builder/v2")
    light_b1 = os.path.join(cosmic_cfg, "com.system76.CosmicTheme.Light.Builder/v1")
    light_b2 = os.path.join(cosmic_cfg, "com.system76.CosmicTheme.Light.Builder/v2")
    dark_t1 = os.path.join(cosmic_cfg, "com.system76.CosmicTheme.Dark/v1")
    dark_t2 = os.path.join(cosmic_cfg, "com.system76.CosmicTheme.Dark/v2")
    light_t1 = os.path.join(cosmic_cfg, "com.system76.CosmicTheme.Light/v1")
    light_t2 = os.path.join(cosmic_cfg, "com.system76.CosmicTheme.Light/v2")
    mode_dir = os.path.join(cosmic_cfg, "com.system76.CosmicTheme.Mode/v1")

    accent_v1_content = 'Some((\n    red: 0.4509804,\n    green: 0.7294118,\n    blue: 0.14509804,\n))\n'
    accent_v2_content = 'Some("#73BA25FF")\n'
    theme_accent_v1 = '''(
    base: (
        red: 0.4509804,
        green: 0.7294118,
        blue: 0.14509804,
        alpha: 1.0,
    ),
    hover: (
        red: 0.396,
        green: 0.643,
        blue: 0.127,
        alpha: 1.0,
    ),
    pressed: (
        red: 0.290,
        green: 0.470,
        blue: 0.093,
        alpha: 1.0,
    ),
    selected: (
        red: 0.396,
        green: 0.643,
        blue: 0.127,
        alpha: 1.0,
    ),
    selected_text: (
        red: 0.4509804,
        green: 0.7294118,
        blue: 0.14509804,
        alpha: 1.0,
    ),
    focus: (
        red: 0.4509804,
        green: 0.7294118,
        blue: 0.14509804,
        alpha: 1.0,
    ),
    divider: (
        red: 0.0,
        green: 0.0,
        blue: 0.0,
        alpha: 1.0,
    ),
    on: (
        red: 0.0,
        green: 0.0,
        blue: 0.0,
        alpha: 1.0,
    ),
    disabled: (
        red: 0.4509804,
        green: 0.7294118,
        blue: 0.14509804,
        alpha: 1.0,
    ),
    on_disabled: (
        red: 0.225,
        green: 0.364,
        blue: 0.072,
        alpha: 1.0,
    ),
    border: (
        red: 0.4509804,
        green: 0.7294118,
        blue: 0.14509804,
        alpha: 1.0,
    ),
    disabled_border: (
        red: 0.4509804,
        green: 0.7294118,
        blue: 0.14509804,
        alpha: 0.5,
    ),
)
'''
    theme_accent_v2 = '''(
    base: "#73BA25FF",
    hover: "#65A420FF",
    pressed: "#4A7817FF",
    selected: "#65A420FF",
    selected_text: "#73BA25FF",
    focus: "#73BA25FF",
    divider: "#000000FF",
    on: "#000000FF",
    disabled: "#73BA25FF",
    on_disabled: "#3A5E12FF",
    border: "#73BA25FF",
    disabled_border: "#73BA2580",
)
'''
    for d in [dark_b1, dark_b2, light_b1, light_b2, dark_t1, dark_t2, light_t1, light_t2, mode_dir]:
        os.makedirs(d, exist_ok=True)

    with open(os.path.join(mode_dir, "is_dark"), "w") as f:
        f.write("true\n")

    for d in [dark_b1, light_b1]:
        with open(os.path.join(d, "accent"), "w") as f:
            f.write(accent_v1_content)
        with open(os.path.join(d, "is_frosted"), "w") as f:
            f.write("true\n")

    for d in [dark_b2, light_b2]:
        with open(os.path.join(d, "accent"), "w") as f:
            f.write(accent_v2_content)
        with open(os.path.join(d, "frosted"), "w") as f:
            f.write("Medium\n")
        for p in ["frosted_panel", "frosted_applets", "frosted_system_interface", "frosted_windows"]:
            with open(os.path.join(d, p), "w") as f:
                f.write("true\n")

    for d in [dark_t1, light_t1]:
        with open(os.path.join(d, "accent"), "w") as f:
            f.write(theme_accent_v1)
        with open(os.path.join(d, "accent_button"), "w") as f:
            f.write(theme_accent_v1)
        with open(os.path.join(d, "is_frosted"), "w") as f:
            f.write("true\n")

    for d in [dark_t2, light_t2]:
        with open(os.path.join(d, "accent"), "w") as f:
            f.write(theme_accent_v2)
        with open(os.path.join(d, "accent_button"), "w") as f:
            f.write(theme_accent_v2)
        for p in ["frosted_panel", "frosted_applets", "frosted_system_interface", "frosted_windows"]:
            with open(os.path.join(d, p), "w") as f:
                f.write("true\n")

    # 2. Ensure fastfetch terminal welcome in user's ~/.bashrc
    bashrc_path = os.path.join(home_dir, ".bashrc")
    ff_snippet = '\n# openSUSE Aether Terminal Greeting\nif [ -t 1 ] && [ -x /usr/bin/fastfetch ] && [ -z "$FASTFETCH_SHOWN" ]; then\n    export FASTFETCH_SHOWN=1\n    /usr/bin/fastfetch\nfi\n'
    if os.path.exists(bashrc_path):
        try:
            with open(bashrc_path, "r") as f:
                bcontent = f.read()
            if "/usr/bin/fastfetch" not in bcontent:
                with open(bashrc_path, "a") as f:
                    f.write(ff_snippet)
        except Exception:
            pass
    else:
        try:
            with open(bashrc_path, "w") as f:
                f.write(ff_snippet)
        except Exception:
            pass

    # Ensure ownership
    if uid is not None and gid is not None:
        for cpath in [cosmic_cfg, bashrc_path]:
            if os.path.exists(cpath):
                if os.path.isdir(cpath):
                    for root, dirs, files in os.walk(cpath):
                        try:
                            os.chown(root, uid, gid)
                        except OSError:
                            pass
                        for f in files:
                            try:
                                os.chown(os.path.join(root, f), uid, gid)
                            except OSError:
                                pass
                else:
                    try:
                        os.chown(cpath, uid, gid)
                    except OSError:
                        pass

# 1. Update /etc/skel so any newly created user gets it automatically
skel_state_dir = "/etc/skel/.local/state/cosmic/com.system76.CosmicBackground/v1"
os.makedirs(skel_state_dir, exist_ok=True)
with open(os.path.join(skel_state_dir, "wallpapers"), "w") as f:
    f.write(content)
ensure_user_theme_and_shell("/etc/skel", None, None)

# 2. Update all existing users with UID >= 1000
for u in pwd.getpwall():
    if 1000 <= u.pw_uid <= 65000 and os.path.isdir(u.pw_dir):
        ensure_user_wallpaper(u.pw_dir, u.pw_uid, u.pw_gid)
        ensure_user_theme_and_shell(u.pw_dir, u.pw_uid, u.pw_gid)

# 3. Check /home/* in case user directory exists but user not in passwd yet
for h in glob.glob("/home/*"):
    if os.path.isdir(h) and not os.path.islink(h):
        try:
            st = os.stat(h)
            if st.st_uid >= 1000:
                ensure_user_wallpaper(h, st.st_uid, st.st_gid)
                ensure_user_theme_and_shell(h, st.st_uid, st.st_gid)
        except OSError:
            pass

# 4. Also update /var/lib/cosmic-greeter
try:
    cg_user = pwd.getpwnam("cosmic-greeter")
    ensure_user_wallpaper("/var/lib/cosmic-greeter", cg_user.pw_uid, cg_user.pw_gid)
    ensure_user_theme_and_shell("/var/lib/cosmic-greeter", cg_user.pw_uid, cg_user.pw_gid)
    cg_cfg = "/var/lib/cosmic-greeter/.config/cosmic/com.system76.CosmicBackground/v1"
    os.makedirs(cg_cfg, exist_ok=True)
    with open(os.path.join(cg_cfg, "all"), "w") as f:
        f.write(f'(\n    output: "all",\n    source: Path("{BG_PATH}"),\n    filter_by_theme: false,\n    rotation_frequency: 300,\n    filter_method: Lanczos,\n    scaling_mode: Zoom,\n    sampling_method: Alphanumeric,\n)\n')
    for root, dirs, files in os.walk("/var/lib/cosmic-greeter"):
        try:
            os.chown(root, cg_user.pw_uid, cg_user.pw_gid)
        except OSError:
            pass
        for f in files:
            try:
                os.chown(os.path.join(root, f), cg_user.pw_uid, cg_user.pw_gid)
            except OSError:
                pass
except KeyError:
    pass
