File: //bigscoots/wpo/nginx/cnf_manager.sh
#!/bin/bash
# BigScoots Managed Infrastructure - Nginx Optimization Suite
# Version: 2.1 (Plan-Aware with MWP Plans)
# 1. Source the environment
if [ -f "/bigscoots/includes/common.sh" ]; then
source /bigscoots/includes/common.sh
fi
assert_lxd_plan
# Parse Flags
DRY_RUN=false
[[ "$*" == *"--dry-run"* ]] && DRY_RUN=true
# 2. Plan Detection via LXD guest API
LXD_PLAN=$(curl -sf --unix-socket /dev/lxd/sock http://lxd/1.0/config/user.plan 2>/dev/null | tr -d '"' || echo "")
[[ -z "$LXD_PLAN" ]] && LXD_PLAN="wpo-starter"
# 3. Define Target Values based on plan
case "$LXD_PLAN" in
wpo-starter)
PLAN="Starter"
TARGET_WORKERS=2
TARGET_CONN=1024
;;
wpo-pro)
PLAN="Professional"
TARGET_WORKERS=4
TARGET_CONN=2048
;;
wpo-business)
PLAN="Business"
TARGET_WORKERS=6
TARGET_CONN=4096
;;
wpo-enterprise)
PLAN="Enterprise"
TARGET_WORKERS=8
TARGET_CONN=4096
;;
mwp-essential75)
PLAN="MWP Essential 75"
TARGET_WORKERS=2
TARGET_CONN=1024
;;
mwp-essential125)
PLAN="MWP Essential 125"
TARGET_WORKERS=4
TARGET_CONN=2048
;;
mwp-essential200)
PLAN="MWP Essential 200"
TARGET_WORKERS=4
TARGET_CONN=2048
;;
mwp-essential300)
PLAN="MWP Essential 300"
TARGET_WORKERS=4
TARGET_CONN=2048
;;
mwp-core500)
PLAN="MWP Core 500"
TARGET_WORKERS=6
TARGET_CONN=4096
;;
mwp-core1000)
PLAN="MWP Core 1000"
TARGET_WORKERS=8
TARGET_CONN=4096
;;
*)
PLAN="Starter (default)"
TARGET_WORKERS=2
TARGET_CONN=1024
;;
esac
# 4. Locate Config and Binary
CONF_FILE="/usr/local/nginx/conf/nginx.conf"
NGINX_BIN="/usr/local/sbin/nginx"
[ ! -f "$NGINX_BIN" ] && NGINX_BIN=$(which nginx)
if [ ! -f "$CONF_FILE" ]; then
echo "[${serverip:-UNKNOWN}] Error: $CONF_FILE not found!" >&2
exit 1
fi
# 5. Extract current values
CURRENT_WORKERS=$(grep -E "^worker_processes" "$CONF_FILE" | awk '{print $2}' | tr -d ';' | head -n1)
CURRENT_CONN=$(grep "worker_connections" "$CONF_FILE" | awk '{print $2}' | tr -d ';' | head -n1)
# 6. Exit quietly if no changes needed
if [ "$CURRENT_WORKERS" == "$TARGET_WORKERS" ] && [ "$CURRENT_CONN" == "$TARGET_CONN" ]; then
exit 0
fi
echo "[${serverip:-UNKNOWN}] Plan: $LXD_PLAN ($PLAN) | Workers: $CURRENT_WORKERS -> $TARGET_WORKERS | Connections: $CURRENT_CONN -> $TARGET_CONN"
# 7. Dry run - show what would change and exit
if [ "$DRY_RUN" = true ]; then
echo "[${serverip:-UNKNOWN}] DRY RUN: No changes applied."
exit 0
fi
# 8. Apply the optimization
cp "$CONF_FILE" "${CONF_FILE}.bak"
sed -i -E "s/^(worker_processes)[[:space:]]+[^;]+;/\1 $TARGET_WORKERS;/" "$CONF_FILE"
sed -i -E "s/(worker_connections)[[:space:]]+[0-9]+;/\1 $TARGET_CONN;/" "$CONF_FILE"
# 9. Verify and reload (graceful - no dropped connections)
RAW_OUTPUT=$($NGINX_BIN -t 2>&1)
NGINX_EXIT_CODE=$?
if [ "$NGINX_EXIT_CODE" -eq 0 ]; then
systemctl reload nginx > /dev/null 2>&1
exit 0
else
TEST_ERRORS=$(echo "$RAW_OUTPUT" | tr '\n' ' ' | sed 's/ */ /g')
echo "[${serverip:-UNKNOWN}] Nginx Config Error: $TEST_ERRORS" >&2
[ -f "${CONF_FILE}.bak" ] && mv "${CONF_FILE}.bak" "$CONF_FILE"
exit 1
fi