#!/bin/bash
set -e

# Minimal postinst: skip actions on upgrade if real users (uid>=1000 excluding initer/nobody) exist.
log(){ echo "[calamares-settings-bianbu] $*" >&2; }

if [ "$1" = configure ]; then
    OLD_VERSION="$2"
    if [ -n "$OLD_VERSION" ] && [ "$OLD_VERSION" != "<none>" ]; then
        REAL_USERS=$(awk -F: '($3>=1000 && $3<65534 && $1!="nobody" && $1!="initer"){print $1}' /etc/passwd | xargs)
        if [ -n "$REAL_USERS" ]; then
            # Optional move of existing config back to share location
            [ -f /etc/sddm.conf ] && mv /etc/sddm.conf /usr/share/calamares/sddm.conf 2>/dev/null || true
            log "Upgrade detected and real users present: $REAL_USERS -> skipping actions."
            exit 0
        fi
    fi
fi

# -------- 正常首次安装或无普通用户升级时执行的动作 --------

# Create installer user if absent
if ! grep -q "^initer:" /etc/passwd; then
    PASSWORD_HASH=$(openssl passwd -6 bianbu)
    useradd -r -m -s '/bin/bash' -c "Bianbu Installer" -p "$PASSWORD_HASH" initer
fi

[ -d /home/initer ] && chown -R initer:initer /home/initer || true
usermod -aG adm,cdrom,dip,lpadmin,plugdev,sudo initer || true

if [ -f /usr/share/calamares/sddm.conf ] && [ ! -f /etc/sddm.conf ]; then
    cp /usr/share/calamares/sddm.conf /etc/sddm.conf
fi

touch /usr/share/calamares/init-ready || true

exit 0