#!/bin/bash
# update-sddm-backgrounds-cache - Read AccountsService wallpapers and embed in theme
# Part of ubuntu-budgie-login SDDM theme AccountsService integration

set -euo pipefail

THEME_DIR="/usr/share/sddm/themes/ubuntu-budgie-login"
COMPONENTS_DIR="$THEME_DIR/components"
CACHE_DIR="$THEME_DIR/cache"
CACHE_FILE="$CACHE_DIR/user-backgrounds.json"
QML_FILE="$COMPONENTS_DIR/AccountsService.qml"
ACCOUNTS_DIR="/var/lib/AccountsService/users"

# Create cache directory if needed
mkdir -p "$CACHE_DIR"

# Use Python to build JSON and generate QML in one go
python3 << 'PYTHON_SCRIPT'
import json
import os
import glob

ACCOUNTS_DIR = "/var/lib/AccountsService/users"
CACHE_FILE = "/usr/share/sddm/themes/ubuntu-budgie-login/cache/user-backgrounds.json"
QML_FILE = "/usr/share/sddm/themes/ubuntu-budgie-login/components/AccountsService.qml"

# Build user backgrounds dictionary
user_backgrounds = {}

if os.path.isdir(ACCOUNTS_DIR):
    for user_file in glob.glob(os.path.join(ACCOUNTS_DIR, "*")):
        if not os.path.isfile(user_file):
            continue

        username = os.path.basename(user_file)

        # Skip system users
        if username in ["sddm", "lightdm", "gdm", "nobody", "root"]:
            continue

        # Read BackgroundFile from user's AccountsService file
        background = None
        try:
            with open(user_file, 'r') as f:
                for line in f:
                    line = line.strip()
                    if line.startswith("BackgroundFile=") or line.startswith("Background="):
                        background = line.split('=', 1)[1]
                        # Strip surrounding quotes
                        background = background.strip().strip('"').strip("'")
                        break
        except Exception:
            continue

        # Only include if file exists AND will be accessible to SDDM greeter
        # SDDM greeter runs as 'sddm' user with limited permissions
        if background and os.path.isfile(background):
            # Check if file is world-readable or in common system directories
            try:
                stat_info = os.stat(background)
                is_world_readable = bool(stat_info.st_mode & 0o004)

                # Common system directories that SDDM can access
                system_paths = [
                    '/usr/share/backgrounds/',
                    '/usr/share/pixmaps/',
                    '/usr/share/wallpapers/',
                    '/var/lib/AccountsService/icons/',
                ]
                is_system_path = any(background.startswith(path) for path in system_paths)

                # Additional check: files in /home are typically not accessible to sddm
                # even if they appear world-readable, due to parent directory permissions
                is_in_home = background.startswith('/home/')

                if is_system_path:
                    # System paths are always accessible
                    user_backgrounds[username] = background
                elif is_world_readable and not is_in_home:
                    # World-readable files outside /home are accessible
                    user_backgrounds[username] = background
                else:
                    # Log skipped file for debugging
                    if is_in_home:
                        print(f"Skipping {username}: {background} (in /home - not accessible to SDDM)")
                    else:
                        print(f"Skipping {username}: {background} (not world-readable)")
            except (OSError, IOError) as e:
                print(f"Skipping {username}: {background} (stat error: {e})")
        elif background:
            print(f"Skipping {username}: {background} (file not found)")

# Write JSON cache
os.makedirs(os.path.dirname(CACHE_FILE), exist_ok=True)
with open(CACHE_FILE, 'w') as f:
    json.dump(user_backgrounds, f, indent=2)

# Generate QML file with embedded JSON
# JSON is already properly escaped by json.dumps
json_data = json.dumps(user_backgrounds)  # This gives us a properly escaped JSON string

qml_content = f'''pragma Singleton
import QtQuick

QtObject {{
    // This data is auto-generated by update-sddm-backgrounds-cache
    // DO NOT EDIT THIS FILE MANUALLY - it will be overwritten
    readonly property string embeddedCacheData: {json.dumps(json_data)}

    property var userBackgrounds: ({{}})
    property bool cacheLoaded: false

    Component.onCompleted: {{
        loadEmbeddedCache()
    }}

    function loadEmbeddedCache() {{
        if (embeddedCacheData.length === 0) {{
            return
        }}

        try {{
            var data = JSON.parse(embeddedCacheData)
            for (var user in data) {{
                userBackgrounds[user] = data[user]
            }}
            cacheLoaded = true
        }} catch (e) {{
            console.error("AccountsService: Failed to parse cache data:", e)
        }}
    }}

    function getUserBackground(username) {{
        if (!username || username.length === 0) {{
            return ""
        }}

        if (userBackgrounds.hasOwnProperty(username)) {{
            return userBackgrounds[username]
        }}

        return ""
    }}
}}
'''

os.makedirs(os.path.dirname(QML_FILE), exist_ok=True)
with open(QML_FILE, 'w') as f:
    f.write(qml_content)

print(f"SDDM backgrounds cache updated successfully")
print(f"Cache file: {CACHE_FILE}")
print(f"QML file: {QML_FILE}")
PYTHON_SCRIPT
