#!/usr/bin/env bash

# Define variables for the script
USER_NAME="devuan"
auto_login="no"
SLIM_CONFIG="/etc/slim.conf"
DEST="/home/${USER_NAME}"

# --- Create the .xinitrc ---
conf_print_xinitrc() {
  cat <<'EOF'
# 1. Define variables
DEFAULT_SESSION=enlightenment_start
session=${1:-$DEFAULT_SESSION}

# 2. Run helper scripts
if [ -d "${HOME}/.xinitrc.d" ]; then
    for f in "${HOME}/.xinitrc.d/"*; do
        [ -x "$f" ] && . "$f"
    done
    unset f
fi

# 3. Export to DBus
if command -v dbus-update-activation-environment >/dev/null; then
    dbus-update-activation-environment --systemd --all
fi

# 4. EXECUTE the session
case $session in
    enlightenment) exec enlightenment_start ;;
    xfce|xfce4)    exec startxfce4 ;;
    *)             exec $session ;;
esac
EOF
}

# Ensure the destination exists and write the file
mkdir -p "${DEST}"
conf_print_xinitrc >"${DEST}/.xinitrc"
chown "${USER_NAME}:${USER_NAME}" "${DEST}/.xinitrc"
chmod +x "${DEST}/.xinitrc"

# --- Configure SLiM ---
# Note: Using '|' as a sed delimiter to avoid conflicts with path slashes
sed -i "s|^.*auto_login.*|auto_login ${auto_login}|" "${SLIM_CONFIG}"
sed -i "s|^.*login_cmd.*|login_cmd exec /bin/bash -login ~/.xinitrc %session|" "${SLIM_CONFIG}"
sed -i "s|^.*default_user.*|default_user ${USER_NAME}|" "${SLIM_CONFIG}"

# Comment out sessiondir to force SLiM to use your .xinitrc logic instead of /usr/share/xsessions
sed -i "s|^sessiondir|# sessiondir|" "${SLIM_CONFIG}"
