HEX
Server: nginx/1.29.3
System: Linux 11979.bigscoots-wpo.com 6.8.0-88-generic #89-Ubuntu SMP PREEMPT_DYNAMIC Sat Oct 11 01:02:46 UTC 2025 x86_64
User: nginx (1068)
PHP: 7.4.33
Disabled: exec,system,passthru,shell_exec,proc_open,proc_close,popen,show_source,cmd# Do not modify this line # 1684243876
Upload Files
File: //proc/self/root/bigscoots/wpo_update.sh
#!/bin/bash
######################################################
# cmupdate
# written by George Liu (eva2000) centminmod.com
######################################################
# variables
#MAINDIR='/etc/centminmod'
CM_INSTALLDIR='/bigscoots'
#############
#if [ -f "${MAINDIR}/custom_config.inc" ]; then
    # default is at /etc/centminmod/custom_config.inc
#    source "${MAINDIR}/custom_config.inc"
#fi

# variables
#############
#branchname=123.09beta01
#DT=$(date +"%d%m%y-%H%M%S")
######################################################
# functions
#############
# set locale temporarily to english
# due to some non-english locale issues
export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8
export LANGUAGE=en_US.UTF-8
export LC_CTYPE=en_US.UTF-8

source /bigscoots/includes/common.sh
source /bigscoots/wpo/extras/bigscoots.menu

fupdate() {
  if [[ -d "${CM_INSTALLDIR}/.git" ]]; then
      cd "${CM_INSTALLDIR}"
      git stash
      if ! grep -q "^github.com" /root/.ssh/known_hosts
      then
        ssh-keyscan github.com >> /root/.ssh/known_hosts
      fi
      git pull [email protected]:jcatello/bigscoots.git
    else
      rm -rf "${CM_INSTALLDIR}"
      cd /
      if ! grep -q "^github.com" /root/.ssh/known_hosts
      then
        ssh-keyscan github.com >> /root/.ssh/known_hosts
      fi
      git clone [email protected]:jcatello/bigscoots.git
    fi >/dev/null 2>&1
} 

# https://stackoverflow.com/questions/4023830/how-to-compare-two-strings-in-dot-separated-version-format-in-bash/70555119#70555119
function compare_versions {
    local a=${1%%.*} b=${2%%.*}
    [[ "10#${a:-0}" -gt "10#${b:-0}" ]] && return 1
    [[ "10#${a:-0}" -lt "10#${b:-0}" ]] && return 2
    a=${1:${#a} + 1} b=${2:${#b} + 1}
    [[ -z $a && -z $b ]] || compare_versions "$a" "$b"
}

ghubsshconf() {
cat <<EOT >> /root/.ssh/config
Host github.com
 HostName github.com
 IdentityFile /root/.bigscoots/rkey
EOT
}

######################################################
PATH=/usr/lib64/ccache:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin:/root/bin

# Ensure Port 22 is open outbound in CSF

if [ -f /etc/csf/csf.conf ]
then
  if ! grep ^TCP_OUT /etc/csf/csf.conf | grep -q '"22,\|,22,\|,22"'
  then
    sed -i '/^TCP_OUT/ s/"$/,22"/g' /etc/csf/csf.conf |grep ^TCP_OUT
    RESTARTCSF=1
  fi
fi

# Ensure CentminMod mirrors for CSF < 15
if command -v csf >/dev/null 2>&1; then
  DOWNLOAD_FILE=/etc/csf/downloadservers
  CSF_MAJOR="$(csf -v 2>/dev/null | sed -n 's/.*v\([0-9][0-9]*\).*/\1/p')"
  if [ -n "$CSF_MAJOR" ] && [ "$CSF_MAJOR" -lt 15 ]; then
    mkdir -p /etc/csf
    cat >"$DOWNLOAD_FILE" <<EOF
download.centminmod.com
download2.centminmod.com
EOF
    csf -u
  fi
fi

if [ ! -f /root/.ssh/config ]
then
  mkdir -p /root/.ssh/
  touch /root/.ssh/config
  chmod 600 /root/.ssh/config
  ghubsshconf
elif 
  ! grep -q github.com /root/.ssh/config
  then
    ghubsshconf
fi

if [ ! -f /root/.bigscoots/rkey ]
then
  mkdir -p /root/.bigscoots
  if ! wget -q -O /root/.bigscoots/rkey https://bigscoots.com/downloads/rkey --no-check-certificate
  then
    bash /bigscoots/general/slack.sh "#wpo-errors" ":warning: $(hostname) -  ${serverip} - Failed to download the repo key."
  else
    chmod 600 /root/.bigscoots/rkey
  fi
else
  if [[ $(stat -L -c "%a" /root/.bigscoots/rkey) != 600 ]]
  then
    chmod 600 /root/.bigscoots/rkey
  fi
fi

fupdate
unset reload

# Check if 'AllowAgentForwarding' is set to 'no' in the sshd_config file
if ! grep -q "^AllowAgentForwarding no" /etc/ssh/sshd_config; then
    # Comment out the existing 'AllowAgentForwarding' line if it exists
    sed -i 's/^AllowAgentForwarding/#&/' /etc/ssh/sshd_config

    # Add 'AllowAgentForwarding no' at the end of the file
    echo "AllowAgentForwarding no" >> /etc/ssh/sshd_config

    # Test SSHD config
    sshd -t &>/dev/null
    if [ $? -ne 0 ]; then
        bash /bigscoots/general/slack.sh "#wpo-errors" ":warning: $(hostname) -  $(hostname -I | awk '{print $1}') - SSH config failed, please check.\n \`\`\`${SSH_ERROR}\`\`\`"
    else
        systemctl restart sshd &>/dev/null
    fi
fi

# CentOS 7 specific checks

if grep -iq 'CentOS Linux release 7' /etc/redhat-release
then
  # Start setting oomscore as low as possible to start kernel from killing it during high memory usage times.
  if [ -d /etc/systemd/system/mariadb.service.d ]
  then
    if [ -f /etc/systemd/system/mariadb.service.d/oomkiller.conf ] && ! grep -q OOMScoreAdjust=-1000 /etc/systemd/system/mariadb.service.d/oomkiller.conf
    then
      echo '[Service]' > /etc/systemd/system/mariadb.service.d/oomkiller.conf
      echo 'OOMScoreAdjust=-1000' >> /etc/systemd/system/mariadb.service.d/oomkiller.conf
      systemctl daemon-reload
      echo '-1000' > /proc/"$(pidof mysqld)"/oom_score_adj
    elif [ ! -f /etc/systemd/system/mariadb.service.d/oomkiller.conf ]
    then
      touch /etc/systemd/system/mariadb.service.d/oomkiller.conf
      echo '[Service]' > /etc/systemd/system/mariadb.service.d/oomkiller.conf
      echo 'OOMScoreAdjust=-1000' >> /etc/systemd/system/mariadb.service.d/oomkiller.conf
      systemctl daemon-reload
      echo '-1000' > /proc/"$(pidof mysqld)"/oom_score_adj
    fi
  fi

  if grep -q mirrorlist.centos.org /etc/yum.repos.d/CentOS-*.repo
  then
    sed -i s/mirrorlist.centos.org/vault.centos.org/g /etc/yum.repos.d/CentOS-*.repo
    sed -i s/^#.*baseurl=http/baseurl=http/g /etc/yum.repos.d/CentOS-*.repo
    sed -i s/mirror.centos.org/vault.centos.org/g /etc/yum.repos.d/CentOS-*.repo
    yum -q clean all
  fi

  if [ -f /etc/csf/csf.conf ]
  then
    if grep -q 'LF_IPSET = "0"' /etc/csf/csf.conf
    then
      sed -i 's/LF_IPSET = "0"/LF_IPSET = "1"/g' /etc/csf/csf.conf
      RESTARTCSF=1
    fi

    if ! command -v ipset >/dev/null 2>&1; then
        if ! rpm -q ipset >/dev/null 2>&1; then
            yum -y -q install ipset
            RESTARTCSF=1
        fi
    fi
  fi

  if [ -s /etc/csf/load.sh ]; then > /etc/csf/load.sh; fi

  [ -f /etc/yum.repos.d/city-fan.org.repo ] && rm -f /etc/yum.repos.d/city-fan.org.repo && yum clean all --quiet

  # Automatic hourly security updates
  #End CentOS 7 specific checks with this fi
fi

# Only run on AlmaLinux
if grep -q "AlmaLinux" /etc/os-release 2>/dev/null; then
    # Install dnf-automatic if not already installed
    rpm -q dnf-automatic &>/dev/null || dnf install -y dnf-automatic &>/dev/null

    # Enforce security-only updates and auto-apply
    sed -i 's/^upgrade_type *=.*/upgrade_type = security/' /etc/dnf/automatic.conf 2>/dev/null
    sed -i 's/^apply_updates *=.*/apply_updates = yes/' /etc/dnf/automatic.conf 2>/dev/null

    # Enable and restart the timer
    systemctl enable --now dnf-automatic.timer &>/dev/null
    systemctl restart dnf-automatic.timer &>/dev/null
fi

# cPanel Specific checks

if [ -d /etc/cpanel ]
then
  if rpm -q yum-cron >/dev/null 2>&1
  then
    yum -y -q remove yum-cron
  fi
fi

 # WPO Specific checks

if [ -f /etc/centminmod-release ]
then 
  if [ ! -f /root/.bigscoots/wpo.installed ] 
  then
    php -v >/dev/null 2>&1
    if [ $? -eq 132 ] 
    then
      bash /bigscoots/wpo/manage/php.sh
    fi
    # Get current hostname
    current_hostname=$(hostname)
    # Extract hostname from the configuration file
    config_file="/usr/local/nginx/conf/conf.d/virtual.conf"
    config_hostname=$(grep 'server_name' $config_file | awk '{print $2}' | tr -d ';')
    # Check if the hostnames match
    if [ "$current_hostname" != "$config_hostname" ]
    then
      # Update the hostname in the configuration file
      sed -i "s/server_name $config_hostname;/server_name $current_hostname;/" $config_file
      NGXRELOAD=1
    fi
  fi

  # quiet combo: ensure certs for virtual.conf hostnames + sync phpMyAdmin if needed
  # ensure certs exist for each server_name in virtual.conf
  awk 'tolower($1)=="server_name"{for(i=2;i<=NF;i++){gsub(/;$/,"",$i);print $i}}' \
    /usr/local/nginx/conf/conf.d/virtual.conf \
    | sort -u | while read -r h; do
      [[ -z "$h" || "$h" == \** || "$h" == *_* ]] && continue
      crt="/usr/local/nginx/conf/ssl/$h.crt"
      key="/usr/local/nginx/conf/ssl/$h.key"
      csr="/usr/local/nginx/conf/ssl/$h.csr"
      mkdir -p /usr/local/nginx/conf/ssl
      if [[ ! -f "$crt" || ! -f "$key" || ! -f "$csr" ]]; then
        if [[ -f "$key" ]]; then
          openssl req -x509 -nodes -key "$key" -days 365 -subj "/CN=$h" -addext "subjectAltName=DNS:$h" -out "$crt" >/dev/null 2>&1
        else
          openssl req -x509 -nodes -newkey rsa:2048 -days 365 -subj "/CN=$h" -addext "subjectAltName=DNS:$h" -keyout "$key" -out "$crt" >/dev/null 2>&1
        fi
        openssl req -new -key "$key" -subj "/CN=$h" -addext "subjectAltName=DNS:$h" -out "$csr" >/dev/null 2>&1
        chmod 600 "$key" 2>/dev/null; chmod 644 "$crt" "$csr" 2>/dev/null
      fi
    done

  # update phpMyAdmin server_name "update-build-image" to the first hostname from virtual.conf
  h="$(
    awk 'tolower($1)=="server_name"{for(i=2;i<=NF;i++){gsub(/;$/,"",$i);print $i}}' \
      /usr/local/nginx/conf/conf.d/virtual.conf \
    | awk '!/^\*/ && $0 !~ /_/ && /^[A-Za-z0-9.-]+$/ {print; exit}'
  )"
  [ -z "$h" ] || {
    sed -i -E "s|^([[:space:]]*server_name[[:space:]]+)update-build-image([[:space:]]*;[[:space:]]*)$|\1$h\2|" \
      /usr/local/nginx/conf/conf.d/phpmyadmin_ssl.conf
    sed -i -E "/^[[:space:]]*server_name[[:space:]]/ s/(^|[[:space:]])update-build-image([[:space:]]|;)/\1$h\2/g" \
      /usr/local/nginx/conf/conf.d/phpmyadmin_ssl.conf
  }

  if [ ! -d /root/.bigscoots/nginx/includes ]
  then
    mkdir -p /root/.bigscoots/nginx/includes
  fi

  if [ ! -d /root/.bigscoots/logs/ssl ]
  then
    mkdir -p /root/.bigscoots/logs/ssl
  fi

  if [ ! -f /root/.acme.sh/acme.sh ]
  then
    /usr/local/src/centminmod/addons/acmetool.sh acmeinstall &>/dev/null
  fi
  
  if [ -f /usr/local/src/centminmod/tools/csfcf.sh ]
  then
    bash /usr/local/src/centminmod/tools/csfcf.sh csf &>/dev/null
  fi

  if [ ! -f /usr/local/nginx/conf/jetpack_whitelist_ip.conf ];then
    bash /usr/local/src/centminmod/tools/jetpackips.sh &>/dev/null
  fi

  if [ ! -f /root/.bigscoots/nginx/includes/staticfiles_images.conf ]
  then
    touch /root/.bigscoots/nginx/includes/staticfiles_images.conf
  fi

  if grep -q wpo33392 /root/.bigscoots/backupinfo
  then
    echo > /root/.bigscoots/backupinfo
  fi

  if ! grep -q  '# Bigscoots Menu' /root/.bashrc
  then
      {
      echo '# Bigscoots Menu'
      echo if [ -f /bigscoots/wpo/extras/bigscoots.menu ]
      echo 'then'
      echo      '. /bigscoots/wpo/extras/bigscoots.menu'
      echo 'fi'
      } >> /root/.bashrc
  fi

  if ! grep -q  '# Bigscoots Whos Online' /root/.bashrc
  then
      {
      echo '# Bigscoots Whos Online'
      echo bash /bigscoots/includes/whosinmeh.sh
      } >> /root/.bashrc
  fi

  if [ -d /home/nginx/domains/demodomain.com ]
  then
    bash /bigscoots/wpo/manage/removedomain.sh demodomain.com
  fi

  if [ -f /usr/local/nginx/conf/xmlrpcblock.conf ]
  then
    if ! grep -q 192.0.64.0 /usr/local/nginx/conf/xmlrpcblock.conf
    then
      {
      echo     allow 192.0.64.0/18\;
      echo     deny all\;
      } >> /usr/local/nginx/conf/xmlrpcblock.conf
    fi
  else
      {
      echo     allow 192.0.64.0/18\;
      echo     deny all\;
      } >> /usr/local/nginx/conf/xmlrpcblock.conf
  fi

  # Update MariaDB repo
  fix_mariadb103_repo

  if grep -q mariadb-maxscale /etc/yum.repos.d/mariadb.repo
  then
    sed -i '/\[mariadb-maxscale\]/,/enabled = [01]/d' /etc/yum.repos.d/mariadb.repo
    if grep -q mariadb-maxscale /etc/yum.repos.d/mariadb.repo
    then
      send_slack_alert "#wpo-alerts" ":warning:" "WPO Update" "$hostname" "Found mariadb-maxscale in \`/etc/yum.repos.d/mariadb.repo\` tried to remove it but it still exists."
    fi
  fi
  # Ensure /bin/bs-backup is a symlink pointing to /opt/bs-backup/bs-backup
  if [ -f /opt/bs-backup/bs-backup ]; then
    if [ ! -L /bin/bs-backup ]; then
      ln -fs /opt/bs-backup/bs-backup /bin/bs-backup
    fi
  fi

  if ! pgrep memcached > /dev/null; then
    for file in /etc/centminmod/php.d/memcache.ini /etc/centminmod/php.d/memcached.ini; do
        [ -f "$file" ] && rm -f "$file"
    done
  fi

  bash /bigscoots/wpo/manage/disk_chk.sh enable

  if [ -d /usr/local/nginx/html/diskusagereports* ]
  then
    rm -rf /usr/local/nginx/html/diskusagereports*
  fi

  if [[ ! -f /etc/centminmod/email-primary.ini ]]; then
   touch /etc/centminmod/email-primary.ini
   echo "root" > /etc/centminmod/email-primary.ini
  fi

  if [[ ! -f /etc/centminmod/email-secondary.ini ]]; then
   touch /etc/centminmod/email-secondary.ini
  fi

  if ! grep -q root /etc/centminmod/email-primary.ini > /dev/null 2>&1 ; then
    echo "root" > /etc/centminmod/email-primary.ini
  fi

  if ! grep -q root /etc/centminmod/email-secondary.ini > /dev/null 2>&1 ; then
    echo "root" > /etc/centminmod/email-secondary.ini
  fi

  # Path to the nginx.conf file
  NGINX_CONF="/usr/local/nginx/conf/nginx.conf"

  # Check if "more_set_headers \"X-Hosted-By: BigScoots\";" exists
  if grep -q 'more_set_headers "X-Hosted-By: BigScoots";' "$NGINX_CONF"; then
      # Check if "more_set_headers \"Server: BigScoots Gateway/1.0.0\";" exists
      if ! grep -q 'more_set_headers "Server: BigScoots Gateway/1.0.0";' "$NGINX_CONF"; then
          # Add "more_set_headers \"Server: BigScoots Gateway/1.0.0\";" below it
          sed -i '/more_set_headers "X-Hosted-By: BigScoots";/a more_set_headers "Server: BigScoots Gateway/1.0.0";' "$NGINX_CONF"
          reload=1
      fi
  else
      # Check if "more_set_headers \"Server: BigScoots Gateway/1.0.0\";" exists
      if grep -q 'more_set_headers "Server: BigScoots Gateway/1.0.0";' "$NGINX_CONF"; then
          # Add "more_set_headers \"X-Hosted-By: BigScoots\";" below it
          sed -i '/more_set_headers "Server: BigScoots Gateway/1.0.0";/a more_set_headers "X-Hosted-By: BigScoots";' "$NGINX_CONF"
          reload=1
      else
          # Add both lines under the opening "http {"
          sed -i '/http {/a more_set_headers "X-Hosted-By: BigScoots";\nmore_set_headers "Server: BigScoots Gateway/1.0.0";' "$NGINX_CONF"
          reload=1
      fi
  fi

  # Check if unwanted lines exist and remove them
  if grep -q 'more_set_headers "Server: nginx centminmod";' "$NGINX_CONF"; then
      sed -i '/more_set_headers "Server: nginx centminmod";/d' "$NGINX_CONF"
      reload=1
  fi

  if grep -q 'more_set_headers "X-Powered-By: centminmod";' "$NGINX_CONF"; then
      sed -i '/more_set_headers "X-Powered-By: centminmod";/d' "$NGINX_CONF"
      reload=1
  fi

  if grep -q '::' /etc/csf/csf.ignore
  then
    sed -i '/::/d' /etc/csf/csf.ignore
  fi

  if grep -q 'IPV6 = "1"' /etc/csf/csf.conf
  then
    sed -i 's/IPV6 = "1"/IPV6 = "0"/g' /etc/csf/csf.conf
  fi

  mkdir -p /root/.bigscoots/php
  touch /etc/centminmod/php.d/zendopcache.ini

  if [ -f /etc/centminmod/php.d/zendopcache.ini ] && grep -q 'opcache.huge_code_pages=[0-9]opcache.blacklist_filename=/root/.bigscoots/php/opcache-blacklist.txt' /etc/centminmod/php.d/zendopcache.ini
  then
    sed -i '/opcache.blacklist_filename/d' /etc/centminmod/php.d/zendopcache.ini
    reload=1
  fi

  if [ -f /etc/centminmod/php.d/zendopcache.ini ] && ! grep -q 'opcache.blacklist_filename=/root/.bigscoots/php/opcache-blacklist.txt' /etc/centminmod/php.d/zendopcache.ini
  then
    echo 'opcache.blacklist_filename=/root/.bigscoots/php/opcache-blacklist.txt' >> /etc/centminmod/php.d/zendopcache.ini
    reload=1
  fi

  if ! grep -q bigscoots-staging.com /root/.bigscoots/php/opcache-blacklist.txt
  then
    echo '/home/nginx/domains/*.bigscoots-staging.com/public/*' >> /root/.bigscoots/php/opcache-blacklist.txt
  fi

  if ! grep -q .maintenance /root/.bigscoots/php/opcache-blacklist.txt
  then
    echo '/home/nginx/domains/*/public/.maintenance' >> /root/.bigscoots/php/opcache-blacklist.txt
  fi

  if ! grep -q '/home/fastcgicache_wp/\*' /root/.bigscoots/php/opcache-blacklist.txt
  then
    echo '/home/fastcgicache_wp/*' >> /root/.bigscoots/php/opcache-blacklist.txt
  fi

  bash /bigscoots/wpo/phpfpm/opcache_blacklist_chk.sh

  if ! grep -q 'log_level = warning' /usr/local/etc/php-fpm.conf
  then
    sed -i '/log_level =/c\log_level = warning' /usr/local/etc/php-fpm.conf
    reload=1
  fi

  if ! grep -q 'pm.process_idle_timeout = 1s;' /usr/local/etc/php-fpm.conf
  then
    sed -i '/pm.process_idle_timeout =/c\pm.process_idle_timeout = 1s;' /usr/local/etc/php-fpm.conf
    reload=1
  fi

  if grep \;request_slowlog_timeout /usr/local/etc/php-fpm.conf >/dev/null 2>&1 ; then 
    sed -i '/;request_slowlog_timeout/c\request_slowlog_timeout = 20' /usr/local/etc/php-fpm.conf
    reload=1
  fi

  if [ -f /usr/local/nginx/conf/phpstatus.conf ] && grep -q '#include /usr/local/nginx/conf/phpstatus.conf' /usr/local/nginx/conf/conf.d/virtual.conf
  then
    sed -i 's|#include /usr/local/nginx/conf/phpstatus.conf;|include /usr/local/nginx/conf/phpstatus.conf;|g' /usr/local/nginx/conf/conf.d/virtual.conf
    NGXRELOAD=1
  fi

  [ -f /root/.bigscoots/backupinfo ] && sed -i '/wpo25535/d' /root/.bigscoots/backupinfo

  # no longer needed since wpo_update.sh will exists on all servers n ow.

  if crontab -l |grep /bigscoots/dedicated/updater.sh > /dev/null 2>&1; then 
    crontab -l | grep -v '/bigscoots/dedicated/updater.sh'  | crontab -
  fi

  if crontab -l |grep /bigscoots/mon_disk.sh > /dev/null 2>&1; then 
    crontab -l | grep -v '/bigscoots/mon_disk.sh'  | crontab -
  fi

  if ! crontab -l |grep /usr/local/src/centminmod/tools/autoprotect.sh | grep '#' > /dev/null 2>&1
  then 
    crontab -l | grep -v '/usr/local/src/centminmod/tools/autoprotect.sh'  | crontab -
    crontab -l | { cat; echo "# 0 */6 * * * /usr/local/src/centminmod/tools/autoprotect.sh >/dev/null 2>&1 # do not uncomment this"; } | crontab -
  fi

  # Define the session cleanup line
  CLEANUP_CRON="*/15 * * * * [ -d /var/opt/remi ] && /usr/bin/find /var/opt/remi/php*/lib/php/session -mindepth 1 -type f -mmin +1440 -delete > /dev/null 2>&1"
  # Check if the line already exists (searching for the unique path to avoid duplicates)
  (crontab -l 2>/dev/null | grep -Fq "/var/opt/remi/php*/lib/php/session") || (
      # If not found, get current crontab, add the line, and re-install
      (crontab -l 2>/dev/null; echo "$CLEANUP_CRON") | crontab -
  )

  # Define the full command string exactly as it should appear
  FULL_CMD="/usr/bin/cmupdate 2>/dev/null ; /bigscoots/wpo_update.sh 2>/dev/null"
  # Define the search pattern (just the script name is enough to find the line)
  SEARCH="/bigscoots/wpo_update.sh"
  # Remove existing version and add the new one at a random Minute and Hour
  (crontab -l 2>/dev/null | grep -v "$SEARCH"; echo "$((RANDOM % 60)) $((RANDOM % 24)) * * * $FULL_CMD") | crontab -

  CORRECT_JOB_COMMAND="bash /bigscoots/wpo/manage/traffic_manager.sh yesterday"
  CORRECT_JOB_PATH="/bigscoots/wpo/manage/traffic_manager.sh"
  INCORRECT_JOB_PATH="/bigscoots/wpo/nginx/trafficstats.sh"

  COUNT=$(crontab -l 2>/dev/null | grep -c -F "$CORRECT_JOB_COMMAND")

  if [ "$COUNT" -eq 1 ]; then
      # GOOD: Job exists. Just clean up the incorrect one, if present.
      crontab -l 2>/dev/null | \
          grep -v -F "$INCORRECT_JOB_PATH" | \
          crontab -
  else
      # BAD: Job is missing or duplicated. Fix it.
      crontab -l 2>/dev/null | \
          grep -v -F "$INCORRECT_JOB_PATH" | \
          grep -v -F "$CORRECT_JOB_PATH" | \
          { cat; echo "$(( RANDOM % 60 )) $(( ( RANDOM % 4 ) + 1 )) * * * $CORRECT_JOB_COMMAND"; } | \
          crontab -
  fi

  LOGROTATECRON='0 0 * * * /usr/sbin/logrotate -s /var/lib/logrotate/logrotate.status /etc/logrotate.conf >/dev/null 2>&1'
  # Check if the line already exists
  ( crontab -l 2>/dev/null | grep -F -q "$LOGROTATECRON" ) || (
    # Add it if not found
    ( crontab -l 2>/dev/null; echo "$LOGROTATECRON" ) | crontab -
  )

  if grep -qs '/backup ' /proc/mounts && ! crontab -l | grep /bigscoots/wpo_backups_ovz.sh | grep -q /bigscoots/wpo/backups/local-backup-cleanup.sh
  then
    NEWCRON=$(crontab -l |grep /bigscoots/wpo_backups_ovz.sh | sed 's/\/bigscoots\/wpo_backups_ovz.sh/\/bigscoots\/wpo_backups_ovz.sh ; \/bigscoots\/wpo\/backups\/local-backup-cleanup.sh/g')
    crontab -l | grep -v '/bigscoots/wpo_backups_ovz.sh'  | crontab -
    crontab -l | { cat; echo "$NEWCRON"; } | crontab -
  fi

  sed -i '/countcpus/d' /usr/local/src/centminmod/inc/nginx_install.inc /usr/local/src/centminmod/inc/centoscheck.inc
  
  if crontab -l |grep -q /usr/local/src/centminmod/inc/wpsetup.inc
  then
    crontab -l | grep -v /usr/local/src/centminmod/inc/wpsetup.inc | crontab -
    crontab -l | { cat; echo "0 */6 * * * /usr/bin/cmupdate 2>/dev/null ; /bigscoots/wpo_update.sh 2>/dev/null"; } | crontab -
  fi

  if ! crontab -l |grep -q 1GSzqc5zuiP8
  then
    crontab -l | { cat; echo "* * * * * /usr/bin/chown -R nginx: /home/nginx/domains/*/public/wp-content/advanced-cache.php # 1GSzqc5zuiP8"; } | crontab -
  fi

  # Define the target script path
  TARGET_SCRIPT="/usr/local/src/centminmod/tools/initial-csf-blocks.sh"
  # Backup the current crontab
  CURRENT_CRONTAB=$(crontab -l 2>/dev/null)

  # Check if the line exists and is uncommented
  if echo "$CURRENT_CRONTAB" | grep -qE "^[^#]*$TARGET_SCRIPT"; then
    # Create a backup before making changes
    echo "$CURRENT_CRONTAB" > "/root/.bigscoots/crontab.$(date +%Y%m%d%H%M%S).backup"
    
    # Comment out the specific line and apply changes
    UPDATED_CRONTAB=$(echo "$CURRENT_CRONTAB" | sed "\|$TARGET_SCRIPT| s|^|#|")
    echo "$UPDATED_CRONTAB" | crontab -
  fi

  # Check for backup cron
  SCRIPT_PATH="/bigscoots/wpo_backups_ovz.sh"
  # Check if the script is already scheduled
  if ! crontab -l 2>/dev/null | grep -qF "$SCRIPT_PATH"; then
      # Generate randomized time
      RANDOM_MINUTE=$((RANDOM % 60))
      RANDOM_HOUR=$((RANDOM % 24))
      # Add the job silently
      (crontab -l 2>/dev/null; echo "$RANDOM_MINUTE $RANDOM_HOUR * * * $SCRIPT_PATH") | crontab - >/dev/null 2>&1
  fi
  # Check for backup cron

  if [ ! -f /root/.bigscoots/nginx/parkpage.disable ]; then
    REMOTE_URL="https://www.bigscoots.com/parked-splash-page/parked.html"
    LOCAL_FILE="/usr/local/nginx/html/index.php"
    MYADMINCONF="/usr/local/nginx/conf/conf.d/phpmyadmin_ssl.conf"

    # If phpMyAdmin SSL conf is missing, build it, then continue
    if [ ! -f "$MYADMINCONF" ]; then
        bash /bigscoots/wpo_json.sh >/dev/null 2>&1 || true
    fi

    # Check if default_server is in any conf file other than virtual.conf and phpmyadmin_ssl.conf
    other_found=$(grep -l 'default_server' /usr/local/nginx/conf/conf.d/*.conf 2>/dev/null | grep -v -E 'virtual.conf|phpmyadmin_ssl.conf')

    # Check if default_server is already in phpmyadmin_ssl.conf
    phpmyadmin_has_default=$(grep -q 'default_server' "$MYADMINCONF" && echo yes || echo no)

    SKIP_VERSION_CHECK=0

    if [ -n "$other_found" ]; then
      : # default_server exists in another config — do nothing
    elif [ "$phpmyadmin_has_default" = "yes" ]; then
      : # already in phpmyadmin_ssl.conf — do nothing
    else
      # Proceed only if the file now exists
      if [ -f "$MYADMINCONF" ]; then
        # Add default_server to listen line
        sed -i 's/listen 443/& default_server/' "$MYADMINCONF"

        # Download parked page
        wget -qO "$LOCAL_FILE" "$REMOTE_URL" && chown nginx: "$LOCAL_FILE"

        # Comment out the 302 redirect if present
        sed -i '/^[[:space:]]*location[[:space:]]*\/[[:space:]]*{/,/}/ {
          /^[[:space:]]*return 302 http:\/\/\$server_name\$request_uri;/ s/^/# /
        }' "$MYADMINCONF"

        NGXRELOAD=1
        SKIP_VERSION_CHECK=1
      fi
    fi >/dev/null 2>&1

    # Version-based update if we didn't already do it
    if [ "$SKIP_VERSION_CHECK" -eq 0 ]; then
      local_ver=$(grep -oP '(?<=<!-- version: ).*?(?= -->)' "$LOCAL_FILE" 2>/dev/null)
      remote_ver=$(curl -s "$REMOTE_URL" | grep -oP '(?<=<!-- version: ).*?(?= -->)')

      if [ -n "$remote_ver" ] && [ "$local_ver" != "$remote_ver" ]; then
        wget -qO "$LOCAL_FILE" "$REMOTE_URL" && chown nginx: "$LOCAL_FILE"
        NGXRELOAD=1
      fi
    fi
  fi

  [ -f /usr/local/nginx/conf/htpassphpmyadmin ] && [ "$(stat -c %a /usr/local/nginx/conf/htpassphpmyadmin)" != "644" ] && chmod 644 /usr/local/nginx/conf/htpassphpmyadmin

  if [ -f /etc/logrotate.d/nginx ] && [ -f /root/.bigscoots/nginx/logrotate.notouch ]; then
    :
  elif [ -f /etc/logrotate.d/nginx ]; then
    if ! grep -q "rotate 30" /etc/logrotate.d/nginx; then
      sed -i 's/rotate.*[0-9]$/rotate 30/g' /etc/logrotate.d/nginx
    fi
  else
    bash /bigscoots/general/slack.sh "#wpo-errors" ":warning: $(hostname) - ${serverip} - /etc/logrotate.d/nginx doesnt exist."
  fi

  if ! rpm -q goaccess >/dev/null 2>&1
  then
    if ! yum -y -q install goaccess >/dev/null 2>&1
    then
      yum-config-manager -q --disable varnish-4.1
      yum -q clean all
      if ! yum -y -q install goaccess >/dev/null 2>&1
      then
        bash /bigscoots/general/slack.sh "#wpo-errors" ":warning: $(hostname) -  ${serverip} - Failed to install goaccess via yum."
      fi
    fi
  fi

  if ! grep -q "1697326996" /usr/bin/ngxreload
  then
    echo 'nginx -t && { [ -f /etc/init.d/nginx ] && /etc/init.d/nginx reload || systemctl reload nginx; } || exit # 1697326996' > /usr/bin/ngxreload
  fi

  if ! grep -q "1697326996" /usr/bin/fpmreload
  then
    echo 'php-fpm -tt && { systemctl reload php-fpm;echo "Reloading php-fpm (via systemctl) [  OK  ]"; } || exit # 1697326996' > /usr/bin/fpmreload
  fi

  if ! grep -q "1697326996" /usr/bin/npreload
  then
    echo '/usr/bin/ngxreload;/usr/bin/fpmreload # 1697326996' > /usr/bin/npreload
  fi

  if ! grep -q "1697326996" /usr/bin/nprestart
  then
    echo '/usr/bin/ngxrestart;/usr/bin/fpmrestart # 1697326996' > /usr/bin/nprestart
  fi

  if ! grep -q "1697326996" /usr/bin/ngxrestart
  then
    echo 'nginx -t && { [ -f /etc/init.d/nginx ] && /etc/init.d/nginx restart || systemctl restart nginx; } || exit # 1697326996' > /usr/bin/ngxrestart
  fi

  if ! crontab -l |grep -q /bigscoots/wpo_update.sh
  then
    crontab -l | grep -v /usr/bin/cmupdate | crontab -
    crontab -l | { cat; echo "0 */6 * * * /usr/bin/cmupdate 2>/dev/null ; /bigscoots/wpo_update.sh 2>/dev/null"; } | crontab -
  fi

  if ! crontab -l |grep -q /bigscoots/mon_mem.sh
  then
    crontab -l | { cat; echo "* * * * * bash /bigscoots/mon_mem.sh"; } | crontab -
  fi

  # Disable serving webp due to Cloudflare

  if [ -f /usr/local/nginx/conf/webp.conf ] && grep -q '".webp";' /usr/local/nginx/conf/webp.conf; then 
    sed -i 's/".webp";/"";/g' /usr/local/nginx/conf/webp.conf
    reload=1
  fi

  if grep -q rocket-nginx/default.conf /usr/local/nginx/conf/conf.d/*.ssl.conf
  then 
    sed -i '/rocket-nginx\/default.conf/d' /usr/local/nginx/conf/conf.d/*.ssl.conf
    reload=1
  fi >/dev/null 2>&1


  if [ ! -f /etc/centminmod/custom_config.inc ]; then
    mkdir -p /etc/centminmod/
    touch /etc/centminmod/custom_config.inc
  fi

  if ! grep -q ENABLEMOTD /etc/centminmod/custom_config.inc; then
    echo "ENABLEMOTD='n'" >> /etc/centminmod/custom_config.inc
    rm -rf /usr/local/bin/dmotd
  fi

  sed -i '/PHP_PGO/d' /etc/centminmod/custom_config.inc

  if grep -q ^log$ /root/.bigscoots/rsync/exclude >/dev/null 2>&1; then
    sed -i '/^log$/d' /root/.bigscoots/rsync/exclude
  fi

  if php -i |grep -q 'session.cookie_secure => 0 => 0' >/dev/null 2>&1
  then
    if [ -f /etc/centminmod/php.d/a_customphp.ini ]
    then 
      echo "session.cookie_secure=1" >> /etc/centminmod/php.d/a_customphp.ini
      reload=1
    fi
  fi

  if find /usr/local/nginx/conf/wpincludes/*/wpsecure_*.conf >/dev/null 2>&1
  then
    find /usr/local/nginx/conf/wpincludes/*/wpsecure_*.conf | while read -r wpsecureconf
    do
      if grep -qF 'location ~* ^/wp-content/uploads/(.+/)?(.+)\.(png|jpe?g)$' "${wpsecureconf}"
      then
        sed -i '/^location ~ \^\/wp-content\/uploads\/ {$/,/^}/d' "${wpsecureconf}"
        reload=1
      fi

      if ! grep -q WzY5FGuoWUObO2Khurof67en54uEFctO "${wpsecureconf}" && [ -f /bigscoots/wpo/nginx/whitelist_plugins.conf ]
      then
        sed -i '/location ~ ^\/(wp-includes\/js\/tinymce\/wp-tinymce.php) {/i include \/bigscoots\/wpo\/nginx\/whitelist_plugins.conf; # WzY5FGuoWUObO2Khurof67en54uEFctO' "${wpsecureconf}"
        reload=1
      fi
    done
  fi

  if ! grep -q fc63a428-6359-400b-8e93-21df2a84fbaa /usr/local/nginx/conf/staticfiles.conf
  then
    mv -f /usr/local/nginx/conf/staticfiles.conf /usr/local/nginx/conf/staticfiles.conf.previous
    cp -rf /bigscoots/wpo/nginx/staticfiles.conf /usr/local/nginx/conf/staticfiles.conf
    NGXRELOAD=1
  fi > /dev/null 2>&1

  [ -f /usr/local/bin/php ] && chown nginx: /usr/local/bin/php

  if [[ $(nginx -t 2>&1) == *"http2_max_"* ]]
  then
     sed -i '/http2_max_/d' /usr/local/nginx/conf/conf.d/*.ssl.conf
     reload=1
   fi

  bash /bigscoots/wpo/extras/phplogging.sh

  if [ -f /root/.acme.sh/account.conf ] && ! grep -q "NOTIFY_LEVEL='0'" /root/.acme.sh/account.conf
  then
    "/root/.acme.sh"/acme.sh --upgrade
    "/root/.acme.sh"/acme.sh --set-notify --notify-level 0
  fi

  ([ ! -s /usr/bin/wp ] || [ ! -s /usr/local/bin/wp ]) && wpcli_update

  # Handle /bin/wp
  if [ ! -f /bin/wp ]; then
      /usr/local/src/centminmod/addons/wpcli.sh install
      wpcli_update
      # Only chmod if it's not already 775
      if [ "$(stat -c '%a' /bin/wp 2>/dev/null)" != "775" ]; then
          chmod 775 /bin/wp
      fi
  fi

  # Handle /usr/bin/wp
  if [ -f /usr/bin/wp ]; then
      # Only chmod if it's not already 755
      if [ "$(stat -c '%a' /usr/bin/wp 2>/dev/null)" != "755" ]; then
          chmod 0755 /usr/bin/wp
      fi
  fi
fi

check_nginx_and_update_http2

# General

if [ -f /etc/postfix/main.cf ] && grep -q "inet_protocols = all" /etc/postfix/main.cf
then
  postconf -e inet_protocols=ipv4
  postfix reload
fi

if crontab -l | grep -q /bigscoots/ovz/node/systemd-session-leak.sh
then
  crontab -l | grep -v '/bigscoots/ovz/node/systemd-session-leak.sh'  | crontab -
fi

# Check if we are in an LXC/LXD container
if [ -f /dev/lxc/console ] || [ -f /run/lxc_start.config ] || grep -qa container=lxc /proc/1/environ; then
    # Only proceed if journalctl is available and journald config exists
    if command -v journalctl >/dev/null 2>&1 && [ -f /etc/systemd/journald.conf ]; then
        
        CONF_FILE="/etc/systemd/journald.conf"
        LIMIT="128M"
        RESTART_NEEDED=0

        # Check and fix RuntimeMaxUse (Memory usage in /run)
        if ! grep -q "^RuntimeMaxUse=$LIMIT" "$CONF_FILE"; then
            sed -i "s/^[#]*RuntimeMaxUse=.*/RuntimeMaxUse=$LIMIT/" "$CONF_FILE"
            RESTART_NEEDED=1
        fi

        # Check and fix SystemMaxUse (Persistent Disk usage)
        if ! grep -q "^SystemMaxUse=$LIMIT" "$CONF_FILE"; then
            sed -i "s/^[#]*SystemMaxUse=.*/SystemMaxUse=$LIMIT/" "$CONF_FILE"
            RESTART_NEEDED=1
        fi

        if [ "$RESTART_NEEDED" -eq 1 ]; then
            # Clean up existing logs immediately to free memory
            journalctl --vacuum-size="$LIMIT" >/dev/null 2>&1
            journalctl --flush >/dev/null 2>&1
            systemctl restart systemd-journald >/dev/null 2>&1
        fi
    fi
fi

if [ ! -f /root/.ssh/id_rsa.pub ]; then
  ssh-keygen -b 4096 -t rsa -f /root/.ssh/id_rsa -q -N "" <<< y >/dev/null 2>&1
fi

if ! crontab -l |grep -q /bigscoots/wpo_update.sh
then
  crontab -l | { cat; echo "0 */6 * * * /bigscoots/wpo_update.sh > /dev/null 2>&1"; } | crontab -
fi

# For sudo
if ! command -v sudo >/dev/null 2>&1; then
    yum -q -y install sudo
fi

[ -d "/var/opt/remi/" ] && find /var/opt/remi/ -user apache -exec chown nginx:nginx {} +

if [ ! -f /etc/vz/vz.conf ] && [ ! -f /root/.bigscoots/imabackupserver ]
then
  /bigscoots/includes/keymebatman.sh
fi

grep -q "74.121.206.158" /root/.ssh/authorized_keys || sed -i 's/from="67.202.70.147"/from="67.202.70.147,74.121.206.158"/' /root/.ssh/authorized_keys

if [ -f /etc/vz/vz.conf ]
then
  if ! crontab -l |grep -q /bigscoots/ovz/node/monitor.sh
  then
    crontab -l | { cat; echo "* * * * * bash /bigscoots/ovz/node/monitor.sh"; } | crontab -
  fi
  if ! crontab -l |grep -q /bigscoots/ovz/node/vzbackup_wrapper.sh
  then
    crontab -l | { cat; echo "0 0 * * * bash /bigscoots/ovz/node/vzbackup_wrapper.sh >/dev/null 2>&1"; } | crontab -
  fi
fi


if [ "$reload" = 1 ] || [ "$NGXRELOAD" = 1 ]; then
    if nginx -t > /dev/null 2>&1; then
        [ "$reload" = 1 ] && scoots php reload all > /dev/null 2>&1
        [ "$NGXRELOAD" = 1 ] && ngxreload > /dev/null 2>&1
    else
      send_slack_alert "#team-chat" ":warning:" "WPO Updates" "NA" "Nginx conf fail during wpo_update run"
    exit 1
  fi
fi

if [ "${RESTARTCSF}" == 1 ]
then
  if ! csf -ra > /dev/null 2>&1
  then
    csf -e  > /dev/null 2>&1
    if ! csf -ra > /dev/null 2>&1
    then
      send_slack_alert "#team-chat" ":warning:" "WPO Updates" "NA" "Tried to restart CSF but it failed, please check me."
    fi
  fi
fi

exit