#!/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 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
}

set_permissions() {
    MPD_HITS_DIRS="/var/lib/mpd-hits /var/run/mpd-hits"
    for i in $MPD_HITS_DIRS; do
        # Create directory if it doesn't exist.
        if ! [ -d "$i" ]; then
            mkdir -p "$i"
        fi

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

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

    # 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
}

mpd_hits_init() {
    # Install initscript.
    update-rc.d mpd-hits defaults >/dev/null

    # (Re)start mpd-hits.
    if [ -x /etc/init.d/mpd-hits ]; then
        if mpd-hits -c >/dev/null; then
            invoke-rc.d mpd-hits restart
        else
            invoke-rc.d mpd-hits start
        fi
    fi
}

add_user_and_group
set_permissions
mpd_hits_init

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

#DEBHELPER#

exit 0
