#!/bin/sh
#
# lxtaz-setup - check that the LXTaz desktop is set up, fix it with --fix.
#
# As a user: the window manager of ~/.config/slitaz/applications.conf
# (slim and startx) and the autostart copies that override the system
# entries. As root: /etc/rcS.conf login manager, lxtaz-dm default
# session, the system and skel applications.conf.
#
# Copyright (C) 2026 SliTaz GNU/Linux - BSD License
# Author: Christophe Lincoln <pankso@slitaz.org>
# AI assistant: Claude (Anthropic)
#

usage() {
	cat <<EOT
Usage: lxtaz-setup [--fix]

Check the LXTaz desktop of the current user (and of the system when run
as root), one line per item. --fix repairs what is wrong.
EOT
}

fix=""
only=""
case "$1" in
	--fix) fix=yes ;;
	--fix-openbox) fix=yes; only=openbox ;;	# lxtaz-session, at login
	"") ;;
	*) usage; exit 1 ;;
esac

errors=0

ok()   { echo "ok    $1"; }
note() { echo "note  $1"; }
bad()  {
	if [ "$fix" ]; then
		echo "fix   $1"
	else
		echo "fail  $1"
		errors=$((errors + 1))
	fi
}

# WINDOW_MANAGER of an applications.conf file: lxtaz-session
check_wm() {
	file="$1"
	if [ ! -f "$file" ]; then
		if [ -f /etc/skel/.config/slitaz/applications.conf ]; then
			bad "$file: missing"
			[ "$fix" ] && mkdir -p "${file%/*}" &&
				cp /etc/skel/.config/slitaz/applications.conf "$file"
		else
			note "$file: missing, nothing to copy it from"
			return
		fi
	fi
	[ -f "$file" ] || return
	wm=$(sed -n 's/^WINDOW_MANAGER="*\([^"]*\)"*.*/\1/p' "$file" | head -n1)
	if [ "$wm" = "lxtaz-session" ]; then
		ok "$file: WINDOW_MANAGER=lxtaz-session"
		return
	fi
	bad "$file: WINDOW_MANAGER=${wm:-(unset)} instead of lxtaz-session"
	[ "$fix" ] || return
	if [ "$wm" ]; then
		sed -i 's/^WINDOW_MANAGER=.*/WINDOW_MANAGER="lxtaz-session"/' "$file"
	else
		printf '\n# Window manager.\nWINDOW_MANAGER="lxtaz-session"\n' >> "$file"
	fi
	# lxde-session when the lxtaz package is removed
	grep -qF 'which $WINDOW_MANAGER' "$file" ||
		echo 'which $WINDOW_MANAGER >/dev/null 2>&1 || WINDOW_MANAGER=lxde-session' \
			>> "$file"
}

# Openbox keybinds of a user rc.xml. lxtaz-ctrl copies the system file
# at the first theme switch, and the copy then misses new defaults: the
# LXDE-only lxpanelctl keys (dead in LXTaz, where lxpanel does not run)
# become the session-aware ones of slitaz-configs 377. Only these lines
# change, the rest of the file is the user's.
check_openbox() {
	rc="${XDG_CONFIG_HOME:-$HOME/.config}/openbox/rc.xml"
	[ -f "$rc" ] || return
	if ! grep -q '<command>lxpanelctl \(run\|menu\)</command>' "$rc" &&
		grep -q 'key="A-F2"' "$rc" && grep -q 'key="C-A-t"' "$rc"; then
		ok "$rc: keybinds"
		return
	fi
	bad "$rc: old keybinds (Super+E, Alt+F2, Ctrl+Alt+T, Ctrl+Alt+Delete)"
	[ "$fix" ] || return

	d=$(mktemp -d) || return
	cat > "$d/fm" <<'EOT'
        <command>sh -c 'case "$XDG_CURRENT_DESKTOP" in LXTaz) exec lxtaz-files ;; *) exec pcmanfm ;; esac'</command>
EOT
	cat > "$d/f2" <<'EOT'
    <keybind key="A-F2">
      <action name="Execute">
        <command>sh -c 'case "$XDG_CURRENT_DESKTOP" in LXTaz) exec lxtaz-dash --show ;; *) exec lxpanelctl run ;; esac'</command>
      </action>
    </keybind>
EOT
	cat > "$d/ct" <<'EOT'
    <keybind key="C-A-t">
      <action name="Execute">
        <startupnotify>
          <enabled>true</enabled>
          <name>Terminal</name>
        </startupnotify>
        <command>sh -c 'case "$XDG_CURRENT_DESKTOP" in LXTaz) command -v tazterm &gt;/dev/null &amp;&amp; exec tazterm ;; esac; exec sakura'</command>
      </action>
    </keybind>
EOT
	addf2=1; grep -q 'key="A-F2"' "$rc" && addf2=0
	addct=1; grep -q 'key="C-A-t"' "$rc" && addct=0
	cp -a "$rc" "$rc.old"
	awk -v d="$d" -v addf2=$addf2 -v addct=$addct '
	function put(f,   l) { while ((getline l < f) > 0) print l; close(f) }
	/<name>App Launcher<\/name>/ { sub(/App Launcher/, "File Manager") }
	/<name>AppMenu<\/name>/ { sub(/AppMenu/, "Logout") }
	/<command>lxpanelctl run<\/command>/ { put(d "/fm"); next }
	/<command>lxpanelctl menu<\/command>/ {
		sub(/lxpanelctl menu/, "lxtaz-logout") }
	/<\/keyboard>/ { if (addf2) put(d "/f2"); if (addct) put(d "/ct") }
	{ print }' "$rc.old" > "$rc"
	rm -rf "$d"
	echo "      old file: $rc.old"
	[ "$DISPLAY" ] && openbox --reconfigure 2>/dev/null
}

if [ "$only" = openbox ]; then
	check_openbox
	exit 0
fi

#
# The lxtaz session itself
#

if command -v lxtaz-session >/dev/null; then
	ok "lxtaz-session installed"
else
	note "lxtaz-session not found: install the lxtaz package"
fi

#
# System (root)
#

if [ "$(id -u)" = 0 ]; then
	# Login manager
	if [ -x /etc/init.d/lxtaz-dm ]; then
		lm=$(sed -n 's/^LOGIN_MANAGER="*\([^"]*\)"*.*/\1/p' /etc/rcS.conf)
		if [ "$lm" = "lxtaz-dm" ]; then
			ok "/etc/rcS.conf: LOGIN_MANAGER=lxtaz-dm"
		else
			bad "/etc/rcS.conf: LOGIN_MANAGER=${lm:-(empty)} instead of lxtaz-dm"
			if [ "$fix" ]; then
				[ -e "/etc/rcS.conf.${lm:-none}" ] ||
					cp -a /etc/rcS.conf "/etc/rcS.conf.${lm:-none}"
				sed -i 's/^LOGIN_MANAGER=.*/LOGIN_MANAGER="lxtaz-dm"/' \
					/etc/rcS.conf
				echo "      old file: /etc/rcS.conf.${lm:-none}, used at next boot"
			fi
		fi
	else
		note "lxtaz-dm not installed: login manager unchanged"
	fi

	# lxtaz-dm default session (dm.conf is kept on upgrades)
	dm=/etc/lxtaz/dm.conf
	if [ -f "$dm" ]; then
		ds=$(sed -n 's/^default-session=//p' "$dm")
		case "$ds" in
			lxtaz) ok "$dm: default-session=lxtaz" ;;
			""|lxde)
				bad "$dm: default-session=${ds:-(empty)} instead of lxtaz"
				[ "$fix" ] && sed -i \
					's/^default-session=.*/default-session=lxtaz/' "$dm" ;;
			*) note "$dm: default-session=$ds (kept, your choice)" ;;
		esac
	fi

	# One lxsession config for LXDE and LXTaz
	if [ -e /etc/xdg/lxsession/LXTaz ]; then
		ok "/etc/xdg/lxsession/LXTaz"
	else
		bad "/etc/xdg/lxsession/LXTaz: missing"
		[ "$fix" ] && ln -sfn LXDE /etc/xdg/lxsession/LXTaz
	fi

	# Root reads the system file, new users get the skel copy
	check_wm /etc/slitaz/applications.conf
	[ -f /etc/skel/.config/slitaz/applications.conf ] &&
		check_wm /etc/skel/.config/slitaz/applications.conf
fi

#
# Current user
#

if [ "$(id -u)" != 0 ]; then
	check_wm "$HOME/.config/slitaz/applications.conf"
fi
check_openbox

# A user autostart entry replaces the system one of the same name. Copies
# made before the LXTaz session (no LXTaz in *ShowIn=) break the session
# split: moved aside to name.desktop.old, which lxsession ignores.
auto="${XDG_CONFIG_HOME:-$HOME/.config}/autostart"
for name in lxtaz-files-desktop lxtaz-dock-daemon lxtaz-dash-daemon \
	lxtaz-ctrl-daemon lxtaz-panel lxpanel pcmanfm; do
	f="$auto/$name.desktop"
	[ -f "$f" ] || continue
	[ -f "/etc/xdg/autostart/$name.desktop" ] || continue
	if grep -q '^[A-Za-z]*ShowIn=.*LXTaz' "$f"; then
		# lxtaz-panel replaced lxpanel in the session: a copy that still
		# runs lxpanel is the user's choice, kept
		if [ "$name" = lxtaz-panel ] && grep -q '^Exec=lxpanel' "$f"; then
			note "$f: keeps lxpanel instead of lxtaz-panel (your choice)"
		else
			ok "$f (LXTaz-aware copy)"
		fi
	else
		bad "$f: old copy, overrides /etc/xdg/autostart/$name.desktop"
		[ "$fix" ] && mv -f "$f" "$f.old"
	fi
done

if [ "$errors" -gt 0 ]; then
	echo "$errors item(s) to fix: lxtaz-setup --fix"
	exit 1
fi
