#!/bin/sh

### BEGIN INIT INFO
# Provides:          tahoe-lafs
# Required-Start:    $network $remote_fs $syslog
# Required-Stop:     $network $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Tahoe-LAFS nodes
### END INIT INFO

# Initscript by bertagaz <bertagaz@ptitcanardnoir.org>
# Heavily reviewed by Zooko O'Whielacronx <zookog@gmail.com>
# and intrigeri <intrigeri@boum.org>.

set -e
set -u

. /lib/lsb/init-functions

DAEMON="/usr/bin/tahoe"
DESC="Tahoe-LAFS secure filesystems"
CONFIG_DIR="/var/lib/tahoe-lafs"
test -x $DAEMON || exit 1
test -d $CONFIG_DIR || exit 1

# Source defaults file; edit that file to configure this script.
DAEMONARGS="--syslog"
AUTOSTART=""

if [ -e /etc/default/tahoe-lafs ]; then
    . /etc/default/tahoe-lafs
fi

nodes_in () {
    local dir="$1"
    cd "$dir" && find ./ -mindepth 1 -maxdepth 1 -type d | cut -c3-
}

node_uid () {
    local node_dir="$1"
    stat -c %U "$CONFIG_DIR/${node_dir}"
}

_tahoe () {
    local action="$1"
    local node_name="$2"
    local node_uid=$(node_uid "$node_name")

    if [ "$node_uid" = "root" ]; then
        log_failure_msg "${node_name} node directory shouldn't be owned by root!"
        return 1
    fi

    case "$action" in
        start|restart)
            su -s "/bin/sh" \
               -c "'$DAEMON' '$action' $DAEMONARGS '$CONFIG_DIR/${node_name}'" \
               "$node_uid"
        ;;
        stop)
            su -s "/bin/sh" \
               -c "'$DAEMON' '$action' '$CONFIG_DIR/${node_name}'" \
               "$node_uid"
        ;;
    esac
}

case "$1" in
start|stop|restart)
    command="$1"
    shift

    log_daemon_msg "$DESC"
    log_progress_msg "\n"

    if [ $# -eq 0 ]; then
        if [ "$AUTOSTART" = "none" ] || [ -z "$AUTOSTART" ]; then
            log_warning_msg " Autostart disabled."
        fi
        if [ "$AUTOSTART" = "all" ]; then
            # all nodes shall be taken care of automatically
            for name in $(nodes_in $CONFIG_DIR); do
                _tahoe "$command" "$name" || STATUS="$?"
            done
        else
            # invoke command only for nodes specified in $AUTOSTART
            for name in $AUTOSTART ; do
                _tahoe "$command" "$name" || STATUS="$?"
            done
        fi
    else
        for name in "$@" ; do
            _tahoe "$command" "$name" || STATUS="$?"
        done
    fi
    log_end_msg "${STATUS:-0}"
    ;;
force-reload)
    shift
    $0 restart "$@"
    ;;
*)
    echo "Usage: $0 {start|stop|restart|force-reload} [node(s)]" >&2
    exit 1
    ;;
esac

exit 0

# vim:set ai sts=2 sw=2 tw=0:
