#!/bin/bash
# Apply Murexia-Light-Grey to the running user session.
# Generated by build_debs.sh — run as your normal user (not root).
set -euo pipefail

THEME_NAME="Murexia-Light-Grey"
ICON_SET_NAME="Murexia-Grey-Theme-Main"
THEME_NAME_X11="${THEME_NAME}-X11"

if [ "$(id -u)" -eq 0 ]; then
    echo "Run this script as your normal user, not root."
    exit 1
fi

if [ ! -f "/usr/share/plasma/look-and-feel/${THEME_NAME}/metadata.json" ]; then
    echo "Theme not found at /usr/share/plasma/look-and-feel/${THEME_NAME}/"
    echo "Make sure the package is installed:  sudo apt install murexia-light-grey"
    exit 1
fi

RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'
CYAN='\033[0;36m'; BOLD='\033[1m'; NC='\033[0m'
ok()   { echo -e "  ${GREEN}✓${NC}  $*"; }
warn() { echo -e "  ${YELLOW}~${NC}  $*"; }
info() { echo -e "  ${CYAN}→${NC}  $*"; }

clear
echo -e "${BOLD}"
echo "  ╔══════════════════════════════════════════════════════════╗"
echo "  ║         MUREXIA KDE PLASMA 6 — THEME ACTIVATOR           ║"
echo "  ╚══════════════════════════════════════════════════════════╝"
echo -e "${NC}"
echo -e "  Theme: ${BOLD}${THEME_NAME}${NC}"
echo -e "  Icons: ${BOLD}${ICON_SET_NAME}${NC}"
echo ""

# ── Tool detection ───────────────────────────────────────────────────────────
HAS_KWRITECONFIG=false; HAS_QDBUS=false; HAS_KVANTUM_MGR=false
HAS_PLASMA_COLORS=false; HAS_PLASMA_LOOKANDFEEL=false
HAS_PLASMA_ICONS=false; HAS_KBUILDSYCOCA=false

command -v kwriteconfig6            &>/dev/null && HAS_KWRITECONFIG=true
command -v qdbus6                   &>/dev/null && HAS_QDBUS=true
command -v kvantummanager           &>/dev/null && HAS_KVANTUM_MGR=true
command -v plasma-apply-colorscheme &>/dev/null && HAS_PLASMA_COLORS=true
{ command -v plasma-apply-lookandfeel &>/dev/null || \
  command -v lookandfeeltool         &>/dev/null; } && HAS_PLASMA_LOOKANDFEEL=true || true
command -v plasma-apply-icons       &>/dev/null && HAS_PLASMA_ICONS=true
command -v kbuildsycoca6            &>/dev/null && HAS_KBUILDSYCOCA=true

echo ""
echo -e "${BOLD}  ──── Applying settings ────${NC}"
echo ""

MANUAL_STEPS=()

if [ "$HAS_KWRITECONFIG" = true ]; then

    kwriteconfig6 --file kdeglobals --group KDE --key widgetStyle kvantum
    ok "Widget style → kvantum"

    if [ "$HAS_PLASMA_COLORS" = true ]; then
        plasma-apply-colorscheme "$THEME_NAME" &>/dev/null \
            && ok "Color scheme applied → $THEME_NAME" \
            || { kwriteconfig6 --file kdeglobals --group General --key ColorScheme "$THEME_NAME"
                 ok "Color scheme configured → $THEME_NAME"; }
    else
        kwriteconfig6 --file kdeglobals --group General --key ColorScheme "$THEME_NAME"
        ok "Color scheme configured → $THEME_NAME"
    fi

    kwriteconfig6 --file plasmarc --group Theme --key name "$THEME_NAME"
    ok "Plasma desktop theme → $THEME_NAME"

    kwriteconfig6 --file kwinrc --group org.kde.kdecoration2 --key library "org.kde.kwin.aurorae"
    kwriteconfig6 --file kwinrc --group org.kde.kdecoration2 --key theme "__aurorae__svg__${THEME_NAME}"
    ok "Window decorations → Aurorae / $THEME_NAME"

    if [ "$HAS_PLASMA_LOOKANDFEEL" = true ]; then
        if command -v plasma-apply-lookandfeel &>/dev/null; then
            plasma-apply-lookandfeel -a "$THEME_NAME" &>/dev/null \
                && ok "Look & feel applied → $THEME_NAME" \
                || { kwriteconfig6 --file kdeglobals --group KDE --key LookAndFeelPackage "$THEME_NAME"
                     ok "Look & feel configured → $THEME_NAME"; }
        else
            lookandfeeltool -a "$THEME_NAME" &>/dev/null \
                && ok "Look & feel applied → $THEME_NAME" \
                || { kwriteconfig6 --file kdeglobals --group KDE --key LookAndFeelPackage "$THEME_NAME"
                     ok "Look & feel configured → $THEME_NAME"; }
        fi
    else
        kwriteconfig6 --file kdeglobals --group KDE --key LookAndFeelPackage "$THEME_NAME"
        ok "Look & feel configured → $THEME_NAME"
    fi

    info "Lockscreen activation handled via systemd drop-in (below)"

    kwriteconfig6 --file kwinrc --group Plugins --key blurEnabled true
    kwriteconfig6 --file kwinrc --group Plugins --key translucencyEnabled true
    ok "Blur effect → enabled"
    kwriteconfig6 --file kwinrc --group Effect-Translucency --key Inactive 100
    kwriteconfig6 --file kwinrc --group Effect-Translucency --key Move 85
    kwriteconfig6 --file kwinrc --group Effect-Translucency --key Menu 85
    kwriteconfig6 --file kwinrc --group Effect-Translucency --key Dialog 85
    kwriteconfig6 --file kwinrc --group Effect-Translucency --key Popup 85
    ok "KWin translucency → 85%"

    if [ "$HAS_PLASMA_ICONS" = true ]; then
        plasma-apply-icons "$ICON_SET_NAME" &>/dev/null \
            && ok "Icon theme applied → $ICON_SET_NAME" \
            || { kwriteconfig6 --file kdeglobals --group Icons --key Theme "$ICON_SET_NAME"
                 ok "Icon theme configured → $ICON_SET_NAME"; }
    else
        kwriteconfig6 --file kdeglobals --group Icons --key Theme "$ICON_SET_NAME"
        ok "Icon theme configured → $ICON_SET_NAME"
    fi

    if systemctl --user is-active cothon-qml.service &>/dev/null; then
        systemctl --user restart cothon-qml.service &>/dev/null \
            && ok "cothon-qml.service restarted" \
            || warn "cothon-qml.service restart failed"
    fi

else
    MANUAL_STEPS+=("Open System Settings → Appearance and apply each component manually")
fi

# ── Kvantum ───────────────────────────────────────────────────────────────────
if [ "$HAS_KVANTUM_MGR" = true ]; then
    kvantummanager --set "$THEME_NAME" &>/dev/null \
        && ok "Kvantum activated → $THEME_NAME" \
        || MANUAL_STEPS+=("Kvantum Manager → select '$THEME_NAME' → Use this theme")
else
    MANUAL_STEPS+=("Kvantum Manager → select '$THEME_NAME' → Use this theme")
fi

# ── Taskbar icon spacing → Small ─────────────────────────────────────────────
_plasma_cfg="$HOME/.config/plasma-org.kde.plasma.desktop-appletsrc"
if [ -f "$_plasma_cfg" ] && command -v python3 &>/dev/null; then
    _result=$(python3 - "$_plasma_cfg" << 'PYEOF'
import sys
cfg = sys.argv[1]
with open(cfg) as f:
    lines = f.readlines()
task_plugins = {'org.kde.plasma.icontasks', 'org.kde.plasma.taskmanager'}
task_prefixes = set()
current_header = None
for line in lines:
    s = line.rstrip()
    if s.startswith('[') and s.endswith(']'):
        current_header = s
    elif current_header and s.startswith('plugin=') and s.split('=', 1)[1].strip() in task_plugins:
        task_prefixes.add(current_header[:-1])
targets = {p + '][Configuration][General]' for p in task_prefixes}
if not targets:
    print('no-task-manager'); sys.exit(0)
result = []; in_target = False; spacing_written = False
for line in lines:
    s = line.rstrip()
    if s.startswith('[') and s.endswith(']'):
        if in_target and not spacing_written:
            result.append('iconSpacing=0\n')
        in_target = s in targets; spacing_written = False; result.append(line)
    elif in_target and s.startswith('iconSpacing='):
        result.append('iconSpacing=0\n'); spacing_written = True
    else:
        result.append(line)
if in_target and not spacing_written:
    result.append('iconSpacing=0\n')
existing_headers = {l.rstrip() for l in result if l.rstrip().startswith('[') and l.rstrip().endswith(']')}
for t in sorted(targets - existing_headers):
    result.append('\n' + t + '\n'); result.append('iconSpacing=0\n')
with open(cfg, 'w') as f:
    f.writelines(result)
print(f'patched:{len(targets)}')
PYEOF
    )
    case "$_result" in
        no-task-manager) warn "No task manager found — re-run after first login" ;;
        patched:*)        ok "Taskbar icon spacing → Small (${_result#patched:} widget(s))" ;;
        *)                warn "Taskbar spacing: unexpected result — $_result" ;;
    esac
else
    [ ! -f "$_plasma_cfg" ] && warn "Plasma config not found — re-run after first login"
fi

# ── Greeter shell drop-ins (lockscreen activation) ───────────────────────────
echo ""
echo -e "${BOLD}  ──── Lockscreen drop-ins ────${NC}"
echo ""
_dropins=(
    "plasma-kwin_wayland.service|${THEME_NAME}"
    "plasma-ksmserver.service|${THEME_NAME_X11}"
)
_daemon_reload=0
for _d in "${_dropins[@]}"; do
    _unit="${_d%|*}"; _shell="${_d#*|}"
    if ! systemctl --user cat "$_unit" >/dev/null 2>&1; then
        warn "Unit $_unit not present — skipping drop-in"
        continue
    fi
    _dropin_dir="$HOME/.config/systemd/user/${_unit}.d"
    _dropin_file="$_dropin_dir/murexia-lockscreen.conf"
    mkdir -p "$_dropin_dir"
    printf '[Service]\nEnvironment=PLASMA_DEFAULT_SHELL=%s\n' "$_shell" > "$_dropin_file"
    ok "Drop-in → $_dropin_file"
    _daemon_reload=1
done
[ "$_daemon_reload" -eq 1 ] && systemctl --user daemon-reload 2>/dev/null || true
info "Logout + login required for lockscreen to take effect"

# ── Konsole profile + default ────────────────────────────────────────────────
# The .deb installs colorscheme + profile to /usr/share/konsole/. KDE looks
# there AND in ~/.local/share/konsole/, but the user's ~/.config/konsolerc
# overrides /etc/xdg/konsolerc — so we must write the user's konsolerc to make
# the theme's profile the default for new Konsole windows. Mirror the profile
# and colorscheme into the user dir for editability, but only if not already
# present (preserves any prior user customisations).
_kuser="$HOME/.local/share/konsole"
mkdir -p "$_kuser"

if [ ! -f "$_kuser/${THEME_NAME}.profile" ] && [ -f "/usr/share/konsole/${THEME_NAME}.profile" ]; then
    cp "/usr/share/konsole/${THEME_NAME}.profile" "$_kuser/${THEME_NAME}.profile"
    ok "Konsole profile mirrored → $_kuser/${THEME_NAME}.profile"
elif [ -f "$_kuser/${THEME_NAME}.profile" ]; then
    info "Konsole profile already present → $_kuser/${THEME_NAME}.profile (preserved)"
fi
if [ ! -f "$_kuser/${THEME_NAME}.colorscheme" ] && [ -f "/usr/share/konsole/${THEME_NAME}.colorscheme" ]; then
    cp "/usr/share/konsole/${THEME_NAME}.colorscheme" "$_kuser/${THEME_NAME}.colorscheme"
fi

if command -v kwriteconfig6 &>/dev/null && \
   { [ -f "$_kuser/${THEME_NAME}.profile" ] || [ -f "/usr/share/konsole/${THEME_NAME}.profile" ]; }; then
    kwriteconfig6 --file konsolerc --group "Desktop Entry" \
        --key "DefaultProfile" "${THEME_NAME}.profile"
    ok "Konsole default profile → ${THEME_NAME}.profile"
fi

# ── Yakuake skin ──────────────────────────────────────────────────────────────
kwriteconfig6 --file yakuakerc --group Appearance --key Skin "$THEME_NAME" 2>/dev/null \
    && ok "Yakuake skin → $THEME_NAME" || true

# ── Refresh services ──────────────────────────────────────────────────────────
echo ""
echo -e "${BOLD}  ──── Refreshing services ────${NC}"
echo ""

rm -rf "${HOME}/.cache/kscreenlocker_greet" 2>/dev/null || true
ok "kscreenlocker QML cache cleared"

[ "$HAS_KBUILDSYCOCA" = true ] && \
    { kbuildsycoca6 --noincremental &>/dev/null && ok "KDE service cache rebuilt" || true; }

if [ "$HAS_QDBUS" = true ]; then
    qdbus6 org.kde.KWin /KWin reconfigure &>/dev/null && ok "KWin reconfigured" || true
    qdbus6 org.kde.plasmashell /PlasmaShell refreshConfig &>/dev/null || true
fi

if command -v qdbus6 &>/dev/null; then
    for _svc in $(qdbus6 | grep org.kde.konsole 2>/dev/null || true); do
        for _sess in $(qdbus6 "$_svc" | grep /Sessions/ 2>/dev/null || true); do
            qdbus6 "$_svc" "$_sess" org.kde.konsole.Session.setProfile \
                "$THEME_NAME" &>/dev/null || true
        done
    done
    ok "Running Konsole sessions refreshed"
fi

SESSION_TYPE="${XDG_SESSION_TYPE:-unknown}"
echo ""
echo -e "  ${YELLOW}Restart plasmashell?${NC} (Applies panel/widget changes)"
[ "$SESSION_TYPE" = "wayland" ] && \
    echo -e "  ${CYAN}Wayland:${NC} Aurorae decorations require a full logout/login."
read -p "  Restart now? [y/N] " -n 1 -r; echo ""
if [[ $REPLY =~ ^[Yy]$ ]]; then
    systemctl --user restart plasma-plasmashell.service &>/dev/null \
        && ok "Plasmashell restarted safely via systemd" \
        || warn "Restart failed — log out and back in"
else
    info "Skipped — log out and back in for full effect"
fi

# ── Summary ───────────────────────────────────────────────────────────────────
echo ""
echo -e "${BOLD}"
echo "  ╔══════════════════════════════════════════════════════════╗"
echo "  ║              ACTIVATION COMPLETE                         ║"
echo "  ╚══════════════════════════════════════════════════════════╝"
echo -e "${NC}"
echo -e "  ${BOLD}${THEME_NAME}${NC} is now active."
echo ""
if [ ${#MANUAL_STEPS[@]} -gt 0 ]; then
    echo -e "  ${YELLOW}Manual steps still needed:${NC}"
    for step in "${MANUAL_STEPS[@]}"; do echo "    • $step"; done
    echo ""
fi
echo "  Always required manually:"
echo "    • Konsole: Settings → Edit Profile → Appearance → $THEME_NAME"
echo "    • Yakuake: Settings → Manage Skins → $THEME_NAME"
echo ""
echo -e "  ${CYAN}Full reset${NC}: log out and back in for guaranteed full effect"
echo ""
