#!/bin/sh

# This tool initialises users within data stores and published data
# directories. It is configured using the contents of the config.sh script.
#
# 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" ] || [ ! "$1" ]; then
    cat 1>&2 <<EOF
Usage: $PROGNAME <calendar user>

Initialise a given calendar user within an existing installation, creating
resources within the given stored data and published data directories...

  * $INSTALL_DIR
  * $WEB_INSTALL_DIR

...respectively.

The resources will be defined as having $IMIP_AGENT_USER as owner.

See $CONFIG for the settings used as described above.

Example:

$PROGNAME mailto:vincent.vole@example.com
EOF
    exit 1
fi

CALENDAR_USER=$1

if [ ! "$CALENDAR_USER" ]; then
    cat 1>&2 <<EOF
Need a calendar user to initialise.
EOF
    exit 1
fi

# Test for a privileged user.

if [ `whoami` != 'root' ]; then
    cat 1>&2 <<EOF
You will need to become a privileged user using su or sudo to run this program
because it changes file ownership.
EOF
    exit 1
fi

# Initialise the directories.

echo "Creating preferences and static Web directories..." 1>&2

for DIR in "$INSTALL_DIR"/preferences "$WEB_INSTALL_DIR"/static ; do
    mkdir -p "$DIR/$CALENDAR_USER"
    chown "$IMIP_AGENT_USER" "$DIR/$CALENDAR_USER"
    chmod g+ws "$DIR/$CALENDAR_USER"
    # Group privileges should already be set.
done

if [ "$STORE_TYPE" = "file" ]; then

    echo "Creating store and journal directories..." 1>&2

    for DIR in "$INSTALL_DIR"/store "$INSTALL_DIR"/journal ; do
        mkdir -p "$DIR/$CALENDAR_USER"
        chown "$IMIP_AGENT_USER" "$DIR/$CALENDAR_USER"
        chmod g+ws "$DIR/$CALENDAR_USER"
        # Group privileges should already be set.
    done
fi
