#!/bin/sh

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.
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

# Initialise the directories.

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