#!/bin/sh
set -e

if [ "$1" = "configure" ]; then
	legacy_home="/opt/var/lib/lemonade"
	new_home="/var/lib/lemonade"

	# Create the lemonade user and group if they don't exist
	if ! getent group lemonade > /dev/null; then
		groupadd lemonade
	fi

	if ! getent passwd lemonade > /dev/null; then
		useradd -m -r -g lemonade -d "$new_home" -s /usr/sbin/nologin lemonade
	fi

	# Move all data from the legacy home
	if [ -d "$legacy_home" ]; then
		usermod -d "$new_home" -m lemonade >/dev/null
	fi

	# Add lemonade user to systemd-journal group for journal access.
	if getent group systemd-journal > /dev/null; then
		usermod -a -G systemd-journal lemonade
	fi

	# Add lemonade user to render group for GPU access
	if getent group render > /dev/null; then
		usermod -a -G render lemonade
	fi
fi

# #2125: migrate pre-fix upgrades — disable per-user lemond.service and stop
# any still-running instance that conflicts with the system service.
if [ "$1" = "configure" ] && [ -n "$2" ] && dpkg --compare-versions "$2" lt "10.10.0~"; then
	if command -v deb-systemd-helper > /dev/null 2>&1; then
		deb-systemd-helper --user disable lemond.service > /dev/null 2>&1 || true
	fi
	if [ -d /run/systemd/system ] && command -v deb-systemd-invoke > /dev/null 2>&1; then
		deb-systemd-invoke --user stop lemond.service > /dev/null 2>&1 || true
	fi
fi

#DEBHELPER#
