#!/bin/sh
set -e

case "$1" in
    configure)
        # Create system user if it doesn't exist.
        if ! id -u ezcoo > /dev/null 2>&1; then
            adduser --system --no-create-home --shell /usr/sbin/nologin \
                    --group --gecos "EZCOO HDMI matrix bridge" ezcoo
        fi

        # Ensure the user is in the dialout group for serial access.
        if getent group dialout > /dev/null 2>&1; then
            adduser ezcoo dialout
        fi

        # Lock down the config directory so only ezcoo can read credentials.
        chown -R root:ezcoo /etc/ezcoo-usb-control
        chmod 750 /etc/ezcoo-usb-control
        chmod 640 /etc/ezcoo-usb-control/config.yaml
        ;;
esac

if [ -d /run/systemd/system ]; then
    systemctl daemon-reload
    systemctl enable ezcoo-usb-control.service
    # Only start automatically on fresh installs, not upgrades.
    if [ "$1" = "configure" ] && [ -z "$2" ]; then
        systemctl start ezcoo-usb-control.service || true
    fi
fi

#DEBHELPER#
