#!/bin/sh

# This tool fixes permissions on data stores and published data, making sure
# that the imip-agent can update the directories involved and that the
# permissions persist.
#
# Copyright (C) 2015, 2016 Paul Boddie <paul@boddie.org.uk>
#
# This program 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.
#
# This program 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
# this program.  If not, see <http://www.gnu.org/licenses/>.

DIRNAME=`dirname "$0"`

if [ -e "$DIRNAME/config.sh" ]; then
    CONFIG="$DIRNAME/config.sh"
    . "$CONFIG"
else
    CONFIG=/etc/imip-agent/config.sh
    . "$CONFIG"
fi

PROGNAME=`basename "$0"`

if [ "$1" = "--help" ]; then
    cat 1>&2 <<EOF
Usage: $PROGNAME

Fix permissions for the stored and published data directories, operating on...

  * $INSTALL_DIR
  * $WEB_INSTALL_DIR

...respectively.

Set ownership and membership to the user and group respectively given as
$IMIP_AGENT_USER and $IMIP_AGENT_GROUP.
EOF
    exit 1
fi

chown -R "$IMIP_AGENT_USER" "$INSTALL_DIR"
chgrp -R "$IMIP_AGENT_GROUP" "$INSTALL_DIR"

for DIR in "$INSTALL_DIR"/preferences "$WEB_INSTALL_DIR"/static ; do
    chown -R "$IMIP_AGENT_USER" "$DIR"
    chgrp -R "$IMIP_AGENT_GROUP" "$DIR"
    chmod -R g+w "$DIR"
done

if [ "$STORE_TYPE" = "file" ]; then
    for DIR in "$INSTALL_DIR"/store "$INSTALL_DIR"/journal ; do
        chown -R "$IMIP_AGENT_USER" "$DIR"
        chgrp -R "$IMIP_AGENT_GROUP" "$DIR"
        chmod -R g+w "$DIR"
    done
fi
