#!/bin/sh -e

# Based on MPD's mpd.postinst script.

# This file is part of mpd-hits.
# Copyright (C) 2003-2005 by Warren Dukes.
# Copyright (C) Decklin Foster.
# Copyright (C) 2010, 2015 Dmitry Samoyloff.
#
# mpd-hits is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option)
# any later version.
#
# mpd-hits is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
# more details.
#
# You should have received a copy of the GNU General Public License along
# with mpd-hits. If not, see <http://www.gnu.org/licenses/>.

umask 0022
ACTION="$1"
VERSION="$2"
CONFIG="/etc/mpd-hits.conf"
USER=mpd-hits
GROUP=mpd-hits

if [ "$ACTION" != "configure" ]; then
    echo "action: $ACTION not supported"
    exit 0
fi

add_user_and_group() {
    # Create group.
    if ! getent group $GROUP >/dev/null; then
        addgroup --quiet --system $GROUP
    fi

    # Create user.
    if ! getent passwd $USER >/dev/null; then
        adduser --quiet --ingroup $GROUP --system --no-create-home \
            --home /var/lib/mpd-hits $USER
    fi
}

process_dir() {
    # Create directory if it doesn't exist.
    if ! [ -d "$1" ]; then
        mkdir -p "$1"
    fi

    # Override dirs' permissions.
    if ! dpkg-statoverride --list --quiet "$1" >/dev/null; then
        dpkg-statoverride --force --quiet --update \
            --add $USER $GROUP "$2" "$1"
    fi

    # Set permissions of files in those dirs.
    for f in `ls "$1"`; do
        chmod -f "$3" "$1/$f"
    done
}

set_permissions() {
    process_dir /var/lib/mpd-hits 0775 0664
    process_dir /var/run/mpd-hits 0755 0644

    # Set permissions of configuration file.
    if ! dpkg-statoverride --list --quiet "$CONFIG" >/dev/null; then
        dpkg-statoverride --force --quiet --update \
            --add $USER $GROUP 0644 "$CONFIG"
    fi
}

add_user_and_group
set_permissions

# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.

#DEBHELPER#

exit 0
