# Shared support for the runnable MongoDB scripts. # This file is sourced and should not itself be executed. gs_mongodb_die() { echo "Error: $*" >&2 exit 1 } gs_mongodb_require_cwd() { script_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) if [ "$PWD" != "$script_dir" ]; then echo "This script must be run from its own directory." >&2 echo "Expected current directory: $script_dir" >&2 echo "Actual current directory: $PWD" >&2 exit 1 fi } gs_mongodb_require_command() { command -v "$1" >/dev/null 2>&1 || gs_mongodb_die "$1 is not in PATH. Run ./INSTALL.sh and source ./SETUP.bash." } gs_mongodb_pid_is_running() { pid_file=$1 [ -f "$pid_file" ] || return 1 pid=$(cat "$pid_file" 2>/dev/null) || return 1 case "$pid" in ''|*[!0-9]*) return 1 ;; esac kill -0 "$pid" 2>/dev/null } gs_mongodb_start_guard() { description=$1 pid_file=$2 if gs_mongodb_pid_is_running "$pid_file"; then echo "$description is already running with PID $(cat "$pid_file")." exit 0 fi if [ -f "$pid_file" ]; then echo "Removing stale PID file: $pid_file" rm -f "$pid_file" fi } gs_mongodb_stop_pidfile() { description=$1 pid_file=$2 timeout=${3:-60} if ! gs_mongodb_pid_is_running "$pid_file"; then echo "$description is not running." rm -f "$pid_file" return 0 fi pid=$(cat "$pid_file") echo "Stopping $description (PID $pid) ..." kill -TERM "$pid" elapsed=0 while kill -0 "$pid" 2>/dev/null; do if [ "$elapsed" -ge "$timeout" ]; then echo "$description did not stop within ${timeout}s." >&2 echo "PID $pid has been left running; SIGKILL was not sent." >&2 return 1 fi sleep 1 elapsed=$((elapsed + 1)) done rm -f "$pid_file" echo "$description stopped." } gs_mongodb_require_cwd GS_MONGODB_SETUP_QUIET_PREVIOUS=${GS_MONGODB_SETUP_QUIET-__unset__} GS_MONGODB_SETUP_QUIET=1 . ./SETUP.bash if [ "$GS_MONGODB_SETUP_QUIET_PREVIOUS" = "__unset__" ]; then unset GS_MONGODB_SETUP_QUIET else GS_MONGODB_SETUP_QUIET=$GS_MONGODB_SETUP_QUIET_PREVIOUS fi unset GS_MONGODB_SETUP_QUIET_PREVIOUS