#!/bin/sh
#
# /etc/rc.d/rc.mongodb
#
# Start/stop/restart the mongodb server.
#
# Runs mongod as the mongo user via clean-exec-sync + setpriv. All
# writable paths (PID, log, data dir) are pre-created and chowned to
# mongo so the daemon never attempts to invoke dac_override or
# dac_read_search, and AppArmor's mongod profile needs no capability
# grants. stderr from the launch is captured to /var/log/mongo/start.log
# for diagnosis.
#

PID=/var/run/mongo/mongo.pid
LOG=/var/log/mongo/mongod.log
STARTLOG=/var/log/mongo/start.log
DBPATH=/var/lib/mongo
CONFIG=/etc/mongod.conf
USER=mongo
GROUP=mongo

mongo_start() {
    mkdir -p /var/run/mongo /var/log/mongo
    chown "$USER:$GROUP" /var/run/mongo /var/log/mongo
    chmod 0755 /var/run/mongo
    chmod 0750 /var/log/mongo

    # Pre-create PID and log as the user that will write them. Using
    # `: >` truncates in place; ownership is then applied to the
    # existing inode rather than relying on O_CREAT inside the daemon.
    : > "$PID"
    : > "$LOG"
    chown "$USER:$GROUP" "$PID" "$LOG"
    chmod 0644 "$PID"
    chmod 0640 "$LOG"

    echo -n "Starting MongoDB "

    # Background the launcher so the shell never blocks on a daemon
    # that may wait for a child readiness signal it never gets.
    # clean-exec-sync closes inherited fds and execs the chain; the
    # `&` is what preserves Ctrl+C and returns control to the shell.
    clean-exec-sync setpriv --reuid="$USER" --regid="$GROUP" --clear-groups \
        /usr/bin/mongod \
            --dbpath="$DBPATH" \
            --config="$CONFIG" \
            --fork \
            --pidfilepath="$PID" \
            --logappend \
            --logpath="$LOG" \
        </dev/null >>"$STARTLOG" 2>&1 &
    LAUNCHER_PID=$!

    # Wait up to 30 seconds for the PID file to be populated with a
    # live pid. mongod's own --fork does the backgrounding; the shell
    # only needs to observe that it succeeded.
    i=0
    while [ $i -lt 30 ]; do
        if [ -s "$PID" ] && kill -0 "$(cat "$PID")" 2>/dev/null; then
            echo "done (pid $(cat "$PID"))."
            return 0
        fi
        # If the launcher exits early and the PID file is not populated,
        # we can stop waiting sooner than 30s.
        if ! kill -0 "$LAUNCHER_PID" 2>/dev/null && [ ! -s "$PID" ]; then
            break
        fi
        echo -n "."
        sleep 1
        i=$((i + 1))
    done

    echo " failed."
    echo "Last 20 lines of $STARTLOG:" >&2
    tail -20 "$STARTLOG" 2>/dev/null >&2
    kill -9 "$LAUNCHER_PID" 2>/dev/null
    return 1
}

mongo_stop() {
    if [ ! -r "$PID" ]; then
        echo "MongoDB is not running (no PID file)."
        return 0
    fi
    PIDVAL=$(cat "$PID")
    if [ -z "$PIDVAL" ]; then
        echo "PID file is empty; removing it."
        rm -f "$PID"
        return 0
    fi
    if kill "$PIDVAL" 2>/dev/null; then
        echo "MongoDB server stopped."
    else
        echo "Failed to stop MongoDB server" >&2
        return 1
    fi
    rm -f "$PID"
}

mongo_restart() {
    mongo_stop
    sleep 2
    mongo_start
}

case "$1" in
    'start')   mongo_start ;;
    'stop')    mongo_stop ;;
    'restart') mongo_restart ;;
	'status')
        if [ ! -r "$PID" ] || [ ! -s "$PID" ]; then
            echo "MongoDB is stopped."
            exit 1
        fi
        PIDVAL=$(cat "$PID")
        if kill -0 "$PIDVAL" 2>/dev/null; then
            echo "MongoDB (pid $PIDVAL) is running."
        else
            echo "MongoDB dead but pid file exists."
            exit 1
        fi
        ;;
    *)         mongo_start ;;   # <-- status, reload, force-quit all hit this
esac