#!/bin/bash
set -e

# Create openlist group if it doesn't exist
if ! getent group openlist >/dev/null; then
    addgroup --system openlist
fi

# Create openlist user if it doesn't exist
if ! getent passwd openlist >/dev/null; then
    # Create user without specifying home directory first
    adduser --system --ingroup openlist --no-create-home --shell /bin/false openlist
fi

# Ensure the home directory exists and has correct ownership
if [ ! -d "/var/lib/openlist" ]; then
    mkdir -p /var/lib/openlist
fi

# Set proper ownership and permissions
chown -R openlist:openlist /var/lib/openlist
chmod 755 /var/lib/openlist

# Set the home directory for the user (this avoids the creation conflict)
usermod --home /var/lib/openlist openlist

# Ensure binary is executable
if [ -f "/var/lib/openlist/openlist" ]; then
    chmod 755 /var/lib/openlist/openlist
fi

# Enable and start the service
systemctl daemon-reload
systemctl enable openlist.service

# Start the service if it's a fresh install
if [ "$1" = "configure" ] && [ -z "$2" ]; then
    systemctl start openlist.service
fi

#DEBHELPER#

exit 0