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: //bigscoots/wpo/extras/wpsetup.inc
wpinstall() {
    if [ ! -f /usr/bin/wp ]; then
      cecho "------------------------------------------------------------" $boldgreen
      cecho "Installing wpcli.sh" $boldyellow
      cecho "------------------------------------------------------------" $boldgreen
      if [ -d "/usr/local/src/centminmod/addons" ]; then
        cd /usr/local/src/centminmod/addons      
      fi
      chmod +x wpcli.sh
      ./wpcli.sh install
    else
      cecho "------------------------------------------------------------" $boldgreen
      cecho "Update wp-cli tool" $boldyellow
      cecho "------------------------------------------------------------" $boldgreen
      if [ -d "/usr/local/src/centminmod/addons" ]; then
        cd /usr/local/src/centminmod/addons      
      fi
      chmod +x wpcli.sh
      ./wpcli.sh update
    fi
}

installredisserver() {
  if [[ "$(ps -C redis-server | grep redis-server >/dev/null 2>&1; echo $?)" != '0' ]]; then
    echo
    echo "Install & Setup Redis Server from REMI YUM Repo"
    echo
    yum -y install redis --enablerepo=remi --disableplugin=priorities
    chkconfig redis on
    if [[ -z "$(grep '^vm.overcommit_memory' /etc/sysctl.conf)" ]]; then
      echo "vm.overcommit_memory = 1" >> /etc/sysctl.conf
      sysctl -p
    fi
    if [ -f /etc/redis.conf ]; then
      if [[ -z "$(grep '^maxmemory 111mb' /etc/redis.conf)" ]]; then
        echo "maxmemory 111mb" >> /etc/redis.conf
        grep '^maxmemory 111mb' /etc/redis.conf
        fi
      if [[ -z "$(grep '^maxmemory-policy allkeys-lru' /etc/redis.conf)" ]]; then
        echo "maxmemory-policy allkeys-lru" >> /etc/redis.conf
        grep '^maxmemory-policy allkeys-lru' /etc/redis.conf
      fi
      if [[ -z "$(grep '^maxmemory-samples 10' /etc/redis.conf)" ]]; then
        echo "maxmemory-samples 10" >> /etc/redis.conf
        grep '^maxmemory-samples 10' /etc/redis.conf
      fi
    fi
    service redis restart
    echo
    echo "Redis server installed with config file at /etc/redis.conf"
    echo
  fi
}

dbsetup() {
  SALT=$(/usr/bin/openssl rand -base64 14 | tr -dc 'a-zA-Z0-9')
  DBN=$RANDOM
  DBNB=$RANDOM
  DBNC=$RANDOM
  DBND=$RANDOM
  DBNE=$RANDOM
  DB="wp${DBNE}${DBN}db_${DBND}"
  DBUSER="wpdb${DBND}u${DBNB}"
  DBPASS="wpdb${SALT}p${DBNC}"
  mysqladmin create $DB
  mysql -e "CREATE USER $DBUSER@'localhost' IDENTIFIED BY '$DBPASS';"
  mysql -e "GRANT index, select, insert, delete, update, create, drop, alter, create temporary tables, execute, lock tables, create view, show view, create routine, alter routine, trigger ON ${DB}.* TO ${DBUSER}@'localhost'; FLUSH PRIVILEGES;"
}

wpinfo_notice() {
# check mysql server is running
mysqladmin -s ping >/dev/null 2>&1
CHECKMYSQL_PING=$?
if [[ "$CHECKMYSQL_PING" -ne '0' ]]; then
  echo
  echo "!!  Error: MariaDB MySQL Server is not running  !!"
  echo "Please make sure MariaDB MySQL Server is running first"
  echo "aborting centmin.sh menu option 22 run..."
  exit
fi
echo
read -ep "Do you want to continue with Nginx vhost site creation ? [y/n] " dovhost_continue
echo

if [[ "$dovhost_continue" != [yY] ]]; then
  echo "aborting Wordpress + Nginx vhost setup..."
  exit
fi
}

sslvhost() {

cecho "---------------------------------------------------------------" $boldyellow
cecho "SSL Vhost Setup..." $boldgreen
cecho "---------------------------------------------------------------" $boldyellow
echo ""

if [[ "$(nginx -V 2>&1 | grep -Eo 'with-http_v2_module')" = 'with-http_v2_module' ]] && [[ "$(nginx -V 2>&1 | grep -Eo 'with-http_spdy_module')" = 'with-http_spdy_module' ]]; then
  HTTPTWO=y
  LISTENOPT='ssl spdy http2'
  COMP_HEADER='spdy_headers_comp 5'
  SPDY_HEADER='add_header Alternate-Protocol  443:npn-spdy/3;'
  # removed in nginx 1.19.7+
  # http://hg.nginx.org/nginx/rev/827202ca1269
  # http://hg.nginx.org/nginx/rev/f790816a0e87
  #HTTPTWO_MAXFIELDSIZE='http2_max_field_size 16k;'
  #HTTPTWO_MAXHEADERSIZE='http2_max_header_size 32k;'
  #HTTPTWO_MAXREQUESTS='http2_max_requests 50000;'
elif [[ "$(nginx -V 2>&1 | grep -Eo 'with-http_v2_module')" = 'with-http_v2_module' ]]; then
  HTTPTWO=y
  if [[ "$(grep -rn listen /usr/local/nginx/conf/conf.d/*.conf | grep -v '#' | grep 443 | grep ' ssl' | grep ' http2' | grep -m1 -o reuseport )" != 'reuseport' ]]; then
    # check if reuseport is supported for listen 443 port - only needs to be added once globally for all nginx vhosts
    NGXVHOST_CHECKREUSEPORT=$(grep --color -Ro SO_REUSEPORT /usr/src/kernels/* | head -n1 | awk -F ":" '{print $2}')
    if [[ "$NGXVHOST_CHECKREUSEPORT" = 'SO_REUSEPORT' ]]; then
      ADD_REUSEPORT=' reuseport'
    else
      ADD_REUSEPORT=""
    fi
    LISTENOPT="ssl http2${ADD_REUSEPORT}"
  else
    LISTENOPT='ssl http2'
  fi
  COMP_HEADER='#spdy_headers_comp 5'
  SPDY_HEADER='#add_header Alternate-Protocol  443:npn-spdy/3;'
  # removed in nginx 1.19.7+
  # http://hg.nginx.org/nginx/rev/827202ca1269
  # http://hg.nginx.org/nginx/rev/f790816a0e87
  #HTTPTWO_MAXFIELDSIZE='http2_max_field_size 16k;'
  #HTTPTWO_MAXHEADERSIZE='http2_max_header_size 32k;'
  #HTTPTWO_MAXREQUESTS='http2_max_requests 50000;'
else
  HTTPTWO=y
  LISTENOPT='ssl http2'
  COMP_HEADER='#spdy_headers_comp 5'
  SPDY_HEADER='#add_header Alternate-Protocol  443:npn-spdy/3;'
fi

if [ ! -f /usr/local/nginx/conf/ssl ]; then
  mkdir -p /usr/local/nginx/conf/ssl
fi

if [ ! -d /usr/local/nginx/conf/ssl/${vhostname} ]; then
  mkdir -p /usr/local/nginx/conf/ssl/${vhostname}
fi

# cloudflare authenticated origin pull cert
# setup https://community.centminmod.com/threads/13847/
if [ ! -d /usr/local/nginx/conf/ssl/cloudflare/${vhostname} ]; then
  mkdir -p /usr/local/nginx/conf/ssl/cloudflare/${vhostname}
  wget${ipv_forceopt_wget} $CLOUDFLARE_AUTHORIGINPULLCERT -O /usr/local/nginx/conf/ssl/cloudflare/${vhostname}/origin.crt
elif [ -d /usr/local/nginx/conf/ssl/cloudflare/${vhostname} ]; then
  wget${ipv_forceopt_wget} $CLOUDFLARE_AUTHORIGINPULLCERT -O /usr/local/nginx/conf/ssl/cloudflare/${vhostname}/origin.crt
fi

if [ ! -f /usr/local/nginx/conf/ssl_include.conf ]; then
cat > "/usr/local/nginx/conf/ssl_include.conf"<<EVS
ssl_session_cache      shared:SSL:10m;
ssl_session_timeout    60m;
ssl_protocols  TLSv1 TLSv1.1 TLSv1.2;  
EVS
fi

cd /usr/local/nginx/conf/ssl/${vhostname}

cecho "---------------------------------------------------------------" $boldyellow
cecho "Generating self signed SSL certificate..." $boldgreen
cecho "CSR file can also be used to be submitted for paid SSL certificates" $boldgreen
cecho "If using for paid SSL certificates be sure to keep both private key and CSR safe" $boldgreen
cecho "creating CSR File: ${vhostname}.csr" $boldgreen
cecho "creating private key: ${vhostname}.key" $boldgreen
cecho "creating self-signed SSL certificate: ${vhostname}.crt" $boldgreen
sleep 9

if [[ -z "$SELFSIGNEDSSL_O" ]]; then
  SELFSIGNEDSSL_O="$vhostname"
else
  SELFSIGNEDSSL_O="$SELFSIGNEDSSL_O"
fi

if [[ -z "$SELFSIGNEDSSL_OU" ]]; then
  SELFSIGNEDSSL_OU="$vhostname"
else
  SELFSIGNEDSSL_OU="$SELFSIGNEDSSL_OU"
fi

if [[ "$SELFSIGNEDSSL_ECDSA" = [yY] ]]; then
  # self-signed ssl cert with SANs for ECDSA
cat > /tmp/reqecc.cnf <<EOF
[req]
default_bits       = 2048
distinguished_name = req_distinguished_name
req_extensions     = v3_req
prompt = no
[req_distinguished_name]
C = ${SELFSIGNEDSSL_C}
ST = ${SELFSIGNEDSSL_ST}
L = ${SELFSIGNEDSSL_L}
O = ${vhostname}
OU = ${vhostname}
CN = ${vhostname}
[v3_req]
keyUsage = keyEncipherment, dataEncipherment
extendedKeyUsage = serverAuth
subjectAltName = @alt_names
[alt_names]
DNS.1 = ${vhostname}
DNS.2 = www.${vhostname}
EOF

cat > /tmp/v3extecc.cnf <<EOF
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names

[alt_names]
DNS.1 = ${vhostname}
DNS.2 = www.${vhostname}
EOF

  openssl ecparam -out ${vhostname}.key -name prime256v1 -genkey
  openssl req -new -sha256 -key ${vhostname}.key -nodes -out ${vhostname}.csr -config /tmp/reqecc.cnf
  openssl x509 -req -days 36500 -sha256 -in ${vhostname}.csr -signkey ${vhostname}.key -out ${vhostname}.crt -extfile /tmp/v3extecc.cnf
  openssl x509 -noout -text < ${vhostname}.crt

  rm -f /tmp/reqecc.cnf
  rm -f /tmp/v3extecc.cnf
else
  # self-signed ssl cert with SANs
cat > /tmp/req.cnf <<EOF
[req]
default_bits       = 2048
distinguished_name = req_distinguished_name
req_extensions     = v3_req
prompt = no
[req_distinguished_name]
C = ${SELFSIGNEDSSL_C}
ST = ${SELFSIGNEDSSL_ST}
L = ${SELFSIGNEDSSL_L}
O = ${vhostname}
OU = ${vhostname}
CN = ${vhostname}
[v3_req]
keyUsage = keyEncipherment, dataEncipherment
extendedKeyUsage = serverAuth
subjectAltName = @alt_names
[alt_names]
DNS.1 = ${vhostname}
DNS.2 = www.${vhostname}
EOF

cat > /tmp/v3ext.cnf <<EOF
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names

[alt_names]
DNS.1 = ${vhostname}
DNS.2 = www.${vhostname}
EOF
  echo
  cat /tmp/req.cnf
  echo
  cat /tmp/v3ext.cnf
  echo
  openssl req -new -newkey rsa:2048 -sha256 -nodes -out ${vhostname}.csr -keyout ${vhostname}.key -config /tmp/req.cnf
  # openssl req -new -newkey rsa:2048 -sha256 -nodes -out ${vhostname}.csr -keyout ${vhostname}.key -subj "/C=${SELFSIGNEDSSL_C}/ST=${SELFSIGNEDSSL_ST}/L=${SELFSIGNEDSSL_L}/O=${vhostname}/OU=${vhostname}/CN=${vhostname}"
  openssl req -noout -text -in ${vhostname}.csr | grep DNS
  openssl x509 -req -days 36500 -sha256 -in ${vhostname}.csr -signkey ${vhostname}.key -out ${vhostname}.crt -extfile /tmp/v3ext.cnf
  # openssl req -x509 -nodes -days 36500 -sha256 -newkey rsa:2048 -keyout ${vhostname}.key -out ${vhostname}.crt -config /tmp/req.cnf
  
  rm -f /tmp/req.cnf
  rm -f /tmp/v3ext.cnf
fi



if [[ ! -f "$(find /usr/local/nginx/conf/ssl -type f -name "dhparam.pem" | head -n1)" ]]; then
  echo
  cecho "---------------------------------------------------------------" $boldyellow
  cecho "Generating dhparam.pem file - can take a few minutes..." $boldgreen 
  dhparamstarttime=$(TZ=UTC date +%s.%N) 
  #openssl dhparam -out dhparam.pem 2048
  dhparamendtime=$(TZ=UTC date +%s.%N)
  DHPARAMTIME=$(echo "$dhparamendtime-$dhparamstarttime"|bc)
  cecho "dhparam file generation time: $DHPARAMTIME" $boldyellow
else
  echo
  cecho "---------------------------------------------------------------" $boldyellow
  cecho "Copy/setup dhparam.pem file..." $boldgreen
  cp -a "$(find /usr/local/nginx/conf/ssl -type f -name "dhparam.pem" | head -n1)" .
fi

}

wpacctsetup() {
PUREUSER=nginx
PUREGROUP=nginx
    if [ "$SECOND_IP" ]; then
      CNIP="$SECOND_IP"
    else
      if [[ "$VPS_GEOIPCHECK_V3" = [yY] ]]; then
        CNIP=$(curl -${ipv_forceopt}s${CURL_TIMEOUTS} -A "$CURL_AGENT Nginx Wordpress Vhost IP CHECK $SCRIPT_VERSION $CURL_CPUMODEL $CURL_CPUSPEED $VPS_VIRTWHAT" https://geoip.centminmod.com/v3 | jq -r '.ip')
      elif [[ "$VPS_GEOIPCHECK_V4" = [yY] ]]; then
        CNIP=$(curl -${ipv_forceopt}s${CURL_TIMEOUTS} -A "$CURL_AGENT Nginx Wordpress Vhost IP CHECK $SCRIPT_VERSION $CURL_CPUMODEL $CURL_CPUSPEED $VPS_VIRTWHAT" https://geoip.centminmod.com/v4 | jq -r '.ip')
      fi
    fi
pureftpinstall

# Support secondary dedicated IP configuration for centmin mod
# nginx vhost generator, so out of the box, new nginx vhosts 
# generated will use the defined SECOND_IP=111.222.333.444 where
# the IP is a secondary IP addressed added to the server.
# You define SECOND_IP variable is centmin mod persistent config
# file outlined at https://centminmod.com/upgrade.html#persistent
# you manually creat the file at /etc/centminmod/custom_config.inc
# and add SECOND_IP=yoursecondary_IPaddress variable to it which
# will be registered with nginx vhost generator routine so that 
# any new nginx vhosts created via centmin.sh menu option 2 or
# /usr/bin/nv or centmin.sh menu option 22, will have pre-defined
# SECOND_IP ip address set in the nginx vhost's listen directive
if [[ -z "$SECOND_IP" ]]; then
  DEDI_IP=""
  DEDI_LISTEN=""
elif [[ "$SECOND_IP" ]]; then
  DEDI_IP=$(echo $(echo ${SECOND_IP}:))
  DEDI_LISTEN="listen   ${DEDI_IP}80;"
fi

wpinstall
  WPSALT=$(/usr/bin/openssl rand -base64 21 | tr -dc 'a-zA-Z0-9')
  WPSALTB=$(/usr/bin/openssl rand -base64 14 | tr -dc 'a-zA-Z0-9')
  WPN=$RANDOM
  WPNB=$RANDOM
  WPADMINUSER="z${WPSALT}wp${WPNB}"
  WPADMINUSER=$(echo $WPADMINUSER | sed -e 's|\/||g' -e 's|\+||g')
  WPADMINPASS="z${WPSALTB}wps${WPN}"
  WPADMINPASS=$(echo $WPADMINPASS | sed -e 's|\/||g' -e 's|\+||g')
 
if [ ! -d /root/tools ]; then
  mkdir -p /root/tools
fi

echo
cecho "-------------------------------------------------------------" $boldyellow
cecho "Setup full Nginx vhost + Wordpress + WP Plugins" $boldgreen
cecho "-------------------------------------------------------------" $boldyellow
echo

wpinfo_notice

read -ep "Enter vhost domain name you want to add (without www. prefix): " vhostname

   # if checkidn_vhost = 0 then internationalized domain name
   checkidn_vhost=$(echo $vhostname | idn | grep '^xn--' >/dev/null 2>&1; echo $?)
   if [[ "$checkidn_vhost" = '0' ]]; then
     vhostname=$(echo $vhostname | idn)
   fi

# check to make sure you don't add a domain name vhost that matches
# your server main hostname setup in server_name within main hostname
# nginx vhost at /usr/local/nginx/conf/conf.d/virtual.conf
if [ -f /usr/local/nginx/conf/conf.d/virtual.conf ]; then
  CHECK_MAINHOSTNAME=$(awk '/server_name/ {print $2}' /usr/local/nginx/conf/conf.d/virtual.conf | sed -e 's|;||')
  if [[ "${CHECK_MAINHOSTNAME}" = "${vhostname}" ]]; then
    echo
    echo " Error: $vhostname is already setup for server main hostname"
    echo " at /usr/local/nginx/conf/conf.d/virtual.conf"
    echo " It is important that main server hostname be setup correctly"
    echo
    echo " As per Getting Started Guide Step 1 centminmod.com/getstarted.html"
    echo " The server main hostname needs to be unique. So please setup"
    echo " the main server name vhost properly first as per Step 1 of guide."
    echo
    echo " Aborting nginx vhost creation..."
    echo
    exit 1
  fi
fi

TESTVHOST=$(echo $vhostname | grep '\/')
while [[ "$TESTVHOST" ]]; do
  echo "!! only domain.com or subdomain.domain.com supported !!"
  echo "   subdirectory is not supported right now"
  read -ep "re-enter vhost domain name you want to add (without www. prefix): " vhostname
  TESTVHOST=$(echo $vhostname | grep '\/')
  echo
done


if [[ "$NGINX_VHOSTSSL" = [yY] ]]; then
  echo
  read -ep "Create a self-signed SSL certificate Nginx vhost? [y/n]: " vhostssl
  if [[ -f "/usr/local/src/centminmod/addons/acmetool.sh" && "$LETSENCRYPT_DETECT" = [yY] ]]; then
    read -ep "Get Letsencrypt SSL certificate Nginx vhost? [y/n]: " vhostssl_le
    if [[ "$vhostssl_le" = [yY] ]]; then
      echo
      echo "You have 4 options: "
      echo "1. issue staging test cert with HTTP + HTTPS (untrusted)"
      echo "2. issue staging test cert with HTTPS default (untrusted)"
      echo "3. issue live cert with HTTP + HTTPS (trusted)"
      echo "4. issue live cert with HTTPS default (trusted)"
      read -ep "Enter option number 1-4: " vhostssl_opt
      if [[ "$vhostssl_opt" = '1' ]]; then
        vhostssl='le'
      elif [[ "$vhostssl_opt" = '2' ]]; then
        vhostssl='led'
        wpcli_ssldefault=1
      elif [[ "$vhostssl_opt" = '3' ]]; then
        vhostssl='lelive'
      elif [[ "$vhostssl_opt" = '4' ]]; then
        vhostssl='lelived'
        wpcli_ssldefault=1
      else
        vhostssl=invalidopt
      fi
      echo
      if [[ "$vhostssl_opt" -eq '2' || "$vhostssl_opt" -eq '4' ]] && [[ "$ISCF_ACHECK" = 'Cloudflare' || "$ISCF_ACHECK" = 'cloudflare' ]]; then
        echo "If using Cloudflare in front of site, disable CF option for"
        echo "Always Use HTTPS in CF Dashboard Crypto Tab as Nginx will do"
        echo "the non-https to https redirect on this end and not require"
        echo "Cloudflare's Always Use HTTPS. If enabled it will cause the"
        echo "error message: too many redirects"
        echo
        echo "Also change Cloudflare Flexible SSL to Full SSL non-strict mode"
        echo
        sleep 1
      fi
    fi # vhostssl_le
  fi
fi

if [[ "$vhostssl" = 'invalidopt' ]]; then
  echo
  echo "error: you entered invalid option = $vhostssl_opt"
  echo "aborting run..."
  exit 1
fi

echo "Theme Setup: "
read -ep "Install CyberChimps Responsive Theme (cyberchimps.com/responsive-theme/) [y/n]: " -i n responsivetheme

echo
echo "Wordpress Setup: "
echo
echo "Not a fan of Gutenberg Editor ? You can switch to Classic Editor"
echo "If you run into Gutenberg Editor issues, you can later switch to"
echo "the Classic Editor https://wordpress.org/plugins/classic-editor/"
read -ep "Install Classic Editor Wordpress Plugin ? [y/n]: " -i y wpclassic_editor

echo
echo "Autoptimize WP Plugin is installed by default. Do you want to install"
echo "companion Autoptimize Gzip Plugin to precompresses js/css optimized files"
echo "details at https://community.centminmod.com/threads/15314/"
read -ep "Install Autoptimize Gzip Companion Wordpress Plugin ? [y/n]: " -i y wpautoptimize_gzip

if [[ "$wpautoptimize_gzip" = [yY] ]]; then
  WP_AUTOPTIMIZE_GZIP='y'
fi

echo
echo "Google Native LazyLoad Plugin https://wordpress.org/plugins/native-lazyload/"
read -ep "Install Google Native LazyLoad Plugin ? [y/n]: " -i y wp_google_lazyload

echo
read -ep "Set custom WP Admin Display Name ? [y/n]: " setdisplayname
if [[ "$setdisplayname" = [yY] ]]; then
  read -ep "Enter Custom WP Admin Display Name: " displayname
  WPADMIN_DISPLAYNAME=$displayname
fi
read -ep "Install Wordpress in subdirectory /blog ? [y/n]: " wpsubdirinstall

if [[ "$wpsubdirinstall" = [yY] ]]; then
  SUBDIR_INSTALL=y
  read -ep "Enter subdirectory name i.e. /blog enter = blog ? : " wpsubdir_value
  WPSUBDIR="/$wpsubdir_value"
  SUBDIR_INCLUDE="include /usr/local/nginx/conf/wpincludes/${vhostname}/wpsecure_${vhostname}.conf;"
  NONSUBDIR_INCLUDE=""
elif [[ "$wpsubdirinstall" != [yY] ]]; then
  SUBDIR_INSTALL=n
  WPSUBDIR=""
  SUBDIR_INCLUDE=""
  NONSUBDIR_INCLUDE="include /usr/local/nginx/conf/wpincludes/${vhostname}/wpsecure_${vhostname}.conf;"
fi

read -ep "Disable Auto Generated WP Admin Username / Password ? [y/n]: " disableautogen
read -ep "Disable wp-login.php password protection ? (less security) [y/n]: " disablepwdprotect

if [[ "$disableautogen" = [yY] ]]; then
  if [ ! -f /usr/sbin/cracklib-check ]; then
    yum -y -q install cracklib
  fi
  echo
  cecho "--------------------------" $boldgreen
  cecho "!! Security Note !!" $boldyellow
  cecho "--------------------------" $boldgreen
  cecho "Please choose a stronger Username/Password Combination" $boldyellow
  echo
  read -ep "Enter desired WP Admin Username: " WPADMINUSER
  read -ep "Enter desired WP Admin Password: " WPADMINPASS

  CHECKWPADMINPASSWD="$(cracklib-check <<<"$WPADMINPASS")"
  okay="$(awk -F': ' '{ print $2}' <<<"$CHECKWPADMINPASSWD")"
  while [[ "$okay" != "OK" ]]; do
    cecho "!! password strength not strong enough !! " $boldyellow
    cecho "!! do not use common dictionary words !! " $boldyellow
    cecho "!! do not use short passwords !! " $boldyellow
    cecho "!! do not use simplistic passwords !! " $boldyellow
    echo
    read -ep "Re-Enter desired WP Admin Password: " WPADMINPASS
    CHECKWPADMINPASSWD="$(cracklib-check <<<"$WPADMINPASS")"
    okay="$(awk -F': ' '{ print $2}' <<<"$CHECKWPADMINPASSWD")"
  done
fi

read -ep "Enter email address for Admin User for Wordpress Installation: " WPADMINEMAIL

# check if nginx server is compiled with default redis nginx modules, 
# otherwise hide redis cache option if nginx server is missing 
# required redis related nginx modules
CHECKFOR_REDISMODULES=$(nginx -V 2>&1 | egrep -o 'ngx_http_redis|redis2-nginx-module|ngx_cache_purge|set-misc-nginx-module' | xargs)
if [[ "$(echo $CHECKFOR_REDISMODULES | grep -o 'ngx_cache_purge')" = 'ngx_cache_purge' ]] && [[ "$(echo $CHECKFOR_REDISMODULES | grep -o 'set-misc-nginx-module')" = 'set-misc-nginx-module' ]] && [[ "$(echo $CHECKFOR_REDISMODULES | grep -o 'redis2-nginx-module')" = 'redis2-nginx-module' ]] && [[ "$(echo $CHECKFOR_REDISMODULES | grep -o 'ngx_http_redis')" = 'ngx_http_redis' ]]; then
  redis_ngx_exists='y'
else
  redis_ngx_exists='n'
fi

echo
cecho "Default is to install KeyCDN WP Cache Enabler Plugin" $boldyellow
cecho "as it's more stable and reliable than WP Super Cache." $boldyellow
if [[ "$redis_ngx_exists" = [yY] ]]; then
  cecho "Redis cache may have issues with caching due to long 6hr cache TTL" $boldyellow
else
  cecho "!! Redis cache not available - no redis nginx modules detected !!" $boldyellow
fi
cecho "You can select which caching method to use below:" $boldyellow
echo

cecho "--------------------------------------------------------" $boldyellow
cecho "        Wordpress Caching               " $boldgreen
cecho "--------------------------------------------------------" $boldyellow
if [[ "$WP_FASTCGI_CACHE" = [yY] ]]; then
  if [[ "$redis_ngx_exists" = [yY] ]]; then
PS3='--------------------------------------------------------
Enter option [ 1 - 4 ] '
select_wpcache_opts=("KeyCDN Cache Enabler" "Redis Nginx Level Caching" "Wordpress Super Cache" "Fastcgi_cache (PHP-FPM)")
  else
PS3='--------------------------------------------------------
Enter option [ 1 - 3 ] '
select_wpcache_opts=("KeyCDN Cache Enabler" "Wordpress Super Cache" "Fastcgi_cache (PHP-FPM)")
  fi
elif [[ "$redis_ngx_exists" = [yY] ]]; then
PS3='--------------------------------------------------------
Enter option [ 1 - 3 ] '
select_wpcache_opts=("KeyCDN Cache Enabler" "Redis Nginx Level Caching" "Wordpress Super Cache")
else
PS3='--------------------------------------------------------
Enter option [ 1 - 2 ] '
select_wpcache_opts=("KeyCDN Cache Enabler" "Wordpress Super Cache")
fi
select optwp in "${select_wpcache_opts[@]}"; do
case $optwp in
  "KeyCDN Cache Enabler" )
    wpscache='n'
    wpcache_option=$REPLY
    echo
    echo "you selected option $wpcache_option (KeyCDN Cache Enabler) [wpscache=$wpscache]"
    echo
    break
    ;;
  "Redis Nginx Level Caching" )
    wpscache='redis'
    wpcache_option=$REPLY
    echo
    echo "you selected option $wpcache_option (Redis Nginx Level Cache) [wpscache=$wpscache]"
    echo
    break
    ;;
  "Wordpress Super Cache" )
    wpscache='y'
    wpcache_option=$REPLY
    echo
    echo "you selected option $wpcache_option (Wordpress Super Cache) [wpscache=$wpscache]"
    echo
    break
    ;;
  "Fastcgi_cache (PHP-FPM)" )
    if [[ "$redis_ngx_exists" = [yY] && "$WP_FASTCGI_CACHE" = [yY] ]]; then
      wpscache='fastcgicache'
    elif [[ "$redis_ngx_exists" = [nN] && "$WP_FASTCGI_CACHE" = [yY] ]]; then
      wpscache='fastcgicache'
    else
      wpscache='n'  
    fi
    wpcache_option=$REPLY
    echo
    echo "you selected option $wpcache_option (Fastcgi_cache PHP-FPM) [wpscache=$wpscache]"
    echo
    break
    ;;
  * )
    echo
    if [[ "$WP_FASTCGI_CACHE" = [yY] ]]; then
      if [[ "$redis_ngx_exists" = [yY] ]]; then
        echo "Valid options are 1 - 4"
      else
        echo "Valid options are 1 - 3"
      fi
    elif [[ "$redis_ngx_exists" = [yY] ]]; then
      echo "Valid options are 1 - 3"
    else
      echo "Valid options are 1 - 2"
    fi
    echo
    ;;
esac
done

TESTEMAIL=$(echo "${WPADMINEMAIL}" |  grep '^[a-zA-Z0-9._%+-]*@[a-zA-Z0-9-]*[\.[a-zA-Z0-9]*]*[a-zA-Z0-9]$')
# echo "$TESTEMAIL"
while [[ "$TESTEMAIL" = "" ]]; do
  echo
  echo "!! make sure email address is valid and typed correctly !!"
  read -ep "Enter email address for Wordpress Installation: " WPADMINEMAIL
  TESTEMAIL=$(echo "${WPADMINEMAIL}" |  grep '^[a-zA-Z0-9._%+-]*@[a-zA-Z0-9-]*[\.[a-zA-Z0-9]*]*[a-zA-Z0-9]$')
  echo
done

if [[ "$PUREFTPD_DISABLED" = [nN] ]]; then
  if [ ! -f /usr/sbin/cracklib-check ]; then
    yum -y -q install cracklib
  fi
  if [ ! -f /usr/bin/pwgen ]; then
    yum -y -q install pwgen
  fi  
  read -ep "Create FTP username for vhost domain (enter username): " ftpuser
  read -ep "Do you want to auto generate FTP password (recommended) [y/n]: " autogenpass

  if [[ "$autogenpass" = [yY] ]]; then
    ftppass=$(pwgen -1cns 27)
  else
    read -ep "Create FTP password for $ftpuser (enter password): " ftppass
  
    # simple password strength check
    # utilise http://cracklib.sourceforge.net/ too
    CHECKPASSWD="$(cracklib-check <<<"$ftppass")"
    okay="$(awk -F': ' '{ print $2}' <<<"$CHECKPASSWD")"
    while [[ "$okay" != "OK" ]]; do
      echo "!! password strength not strong enough !! "
      echo "!! do not use common dictionary words !! "
      echo "!! do not use short passwords !! "
      echo "!! do not use simplistic passwords !! "
      echo
      read -ep "re-enter FTP password for $ftpuser (enter password): " ftppass
      CHECKPASSWD="$(cracklib-check <<<"$ftppass")"
      okay="$(awk -F': ' '{ print $2}' <<<"$CHECKPASSWD")"
    done
  fi # autogenpass
  echo
  echo "FTP username you entered: $ftpuser"
  if [[ "$autogenpass" = [yY] ]]; then
    echo "FTP password auto generated: $ftppass"
  else
    echo "FTP password you entered: $ftppass"    
  fi
fi

if [ ! -d /home/nginx/domains/$vhostname ]; then

dbsetup

# Checking Permissions, making directories, example index.html
umask 027
mkdir -p /home/nginx/domains/$vhostname/{public,private,log,backup}
ngx_logformats
if [[ "$wpsubdirinstall" = [yY] ]]; then
  mkdir -p /home/nginx/domains/$vhostname/public/$wpsubdir_value
fi

if [ ! -f /usr/local/nginx/conf/wpincludes ]; then
  mkdir -p /usr/local/nginx/conf/wpincludes
fi

if [ ! -f "/usr/local/nginx/conf/wpincludes/$vhostname" ]; then
  mkdir -p "/usr/local/nginx/conf/wpincludes/$vhostname"
fi

if [[ "$PUREFTPD_DISABLED" = [nN] ]]; then
  ( echo "${ftppass}" ; echo "${ftppass}" ) | pure-pw useradd "$ftpuser" -u $PUREUSER -g $PUREGROUP -d "/home/nginx/domains/$vhostname"
  pure-pw mkdb
fi

cp -R $CUR_DIR/htdocs/custom_errorpages/* /home/nginx/domains/$vhostname/public
umask 022
chown -R nginx:nginx "/home/nginx/domains/$vhostname"
find "/home/nginx/domains/$vhostname" -type d -exec chmod g+s {} \;

# rate limit setup
WPRATECHECK=$(grep 'zone=xwplogin' /usr/local/nginx/conf/nginx.conf)
WPRATERPCCHECK=$(grep 'zone=xwprpc' /usr/local/nginx/conf/nginx.conf)

if [[ -z "$WPRATERPCCHECK" ]]; then
  sed -i 's/http {/http { \nlimit_req_zone $binary_remote_addr zone=xwprpc:10m rate=30r\/s;\n/g' /usr/local/nginx/conf/nginx.conf
fi

if [[ -z "$WPRATECHECK" ]]; then
  sed -i 's/http {/http { \nlimit_req_zone $binary_remote_addr zone=xwplogin:10m rate=40r\/m;\n/g' /usr/local/nginx/conf/nginx.conf
fi

################################################################################
# create wp super cache's included php config file php-wpsc.conf
\cp -f /usr/local/nginx/conf/php.conf /usr/local/nginx/conf/php-wpsc.conf
sed -i "s|fastcgi_param  SERVER_NAME        \$server_name;|fastcgi_param  SERVER_NAME        \$http_host;|" /usr/local/nginx/conf/php-wpsc.conf

################################################################################
# create wp enable enabler included files https://community.centminmod.com/posts/21220/

cat > "/usr/local/nginx/conf/wpincludes/${vhostname}/wpcacheenabler_${vhostname}.conf"<<HFA
    # Block nginx-help log from public viewing
    location ~* /wp-content/uploads/nginx-helper/ { deny all; }

    set \$cache_uri \$request_uri;

    # exclude mobile devices from redis caching
    if (\$cmwpcache_device = mobile) { set \$cache_uri 'nullcache'; }

    # bypass cache if POST requests or URLs with a query string
    if (\$request_method = POST) {
        set \$cache_uri 'nullcache';
    }
    if (\$query_string != "") {
        set \$cache_uri 'nullcache';
    }

    # include query strings fbclid, gclid, utm in cache via stripping them with
    # 302 redirect via mapping in /usr/local/nginx/conf/wpcacheenabler_map.conf
    if (\$q_ignorearg) {
      set \$check_qurl \$request_uri;
      set \$check_surl \$request_uri;
      set \$cache_uri \$uri;
      #rewrite ^ \$uri? redirect;
    }
    add_header Check-Querystring-Uri "\$check_qurl";
    #add_header Q-Ignore-Arg "\$q_ignorearg";

    # bypass cache if URLs containing the following strings
    if (\$request_uri ~* "(\?add-to-cart=|\?wc-ajax=|\?wc-api=|/cart/|/my-account/|/checkout/|/shop/checkout/|/wp-json/|/store/checkout/|/customer-dashboard/|/addons/|/wp-admin/|/xmlrpc.php|/wp-(app|cron|login|register|mail).php|wp-.*.php|/feed/|index.php|wp-comments-popup.php|wp-links-opml.php|wp-locations.php|sitemap(_index)?.xml|[a-z0-9_-]+-sitemap([0-9]+)?.xml)") {
        set \$cache_uri 'nullcache';
    }

    # bypass cache if the cookies containing the following strings
    if (\$http_cookie ~* "comment_author|wordpress_[a-f0-9]+|wp-postpass|wordpress_logged_in|wc-api|edd_items_in_cart|woocommerce_items_in_cart|woocommerce_cart_hash|woocommerce_recently_viewed|wc_session_cookie_HASH|wp_woocommerce_session_|wptouch_switch_toggle") {
        set \$cache_uri 'nullcache';
    }

    # bypass cache for woocommerce
    if (\$arg_add-to-cart != "") { set \$cache_uri 'nullcache'; }
    if (\$arg_wc-api != "") { set \$cache_uri 'nullcache'; }

    ## bypass cache for empty woocommerce carts
    #if (\$cookie_woocommerce_items_in_cart != "0") { 
    #  set \$cache_uri 'nullcache';
    #}

    # custom sub directory e.g. /blog
    set \$custom_subdir '${WPSUBDIR}';
    #if (\$args ~* s=(.*)) {
    #  set \$cache_uri \$request_uri;
    #  set \$check_surl \$cache_uri;
    #  set \$cache_uri /search/\$1;
    #}
    #add_header Check-Uri "\$check_surl";
    #add_header Set-Uri "\$cache_uri";

    # default html file
    set \$cache_enabler_uri '\${custom_subdir}/wp-content/cache/cache-enabler/\${http_host}\${cache_uri}\${scheme}-index.html';

    # webp html file
    if (\$http_accept ~* "image/webp") {
        set \$cache_enabler_uri_webp '\${custom_subdir}/wp-content/cache/cache-enabler/\${http_host}\${cache_uri}\${scheme}-index-webp.html';
    }

    #if (-f \$document_root\$cache_enabler_uri) {
    #set \$cttls "120s";
    #}
    #expires \$cttls;
HFA

cat > "/usr/local/nginx/conf/wpcacheenabler_map.conf"<<HFB
map \$http_user_agent \$cmwpcache_device {
    default                                     'desktop';
    ~*(iPad|iPhone|Android|IEMobile|Blackberry) 'mobile';
    "~*Firefox.*Mobile"                         'mobile';
    "~*ipod.*mobile"                            'mobile';
    "~*Opera\ Mini"                             'mobile';
    "~*Opera\ Mobile"                           'mobile';
    "~*Mobile"                                  'mobile';
    "~*Tablet"                                  'mobile';
    "~*Kindle"                                  'mobile';
    "~*Windows\ Phone"                          'mobile';
}

map \$args \$q_ignorearg {
  default               0;
  "~*fbclid"            1;
  "~*gclid"             1;
  "~*utm"               1;
  "~*fb_action_ids"     1;
  "~*fb_action_types"   1;
  "~*fb_source"         1;
  "~*age-verified"      1;
  "~*ao_noptimize"      1;
  "~*usqp"              1;
  "~*cn-reloaded"       1;
  "~*_ga"               1;
  "~*_ke"               1;
  "~*mc_cid"            1;
  "~*mc_eid"            1;
  "~*ref"               1;
}
HFB

WPCACHEENABLERMAP_INCLUDECHECK=$(grep '\/usr\/local\/nginx\/conf\/wpcacheenabler_map.conf' /usr/local/nginx/conf/nginx.conf)
  if [[ -z "$WPCACHEENABLERMAP_INCLUDECHECK" ]]; then
    echo
    echo "include file /usr/local/nginx/conf/wpcacheenabler_map.conf add to nginx.conf"
      sed -i 's|\/usr\/local\/nginx\/conf\/fastcgi_param_https_map.conf;|\/usr\/local\/nginx\/conf\/fastcgi_param_https_map.conf;\ninclude \/usr\/local\/nginx\/conf\/wpcacheenabler_map.conf;|g' /usr/local/nginx/conf/nginx.conf
  fi

################################################################################
# create nginx level redis cache included php config file php-rediscache.conf
# https://community.centminmod.com/posts/18828/
# \cp -f /usr/local/nginx/conf/php.conf /usr/local/nginx/conf/php-rediscache.conf

cat > "/usr/local/nginx/conf/php-rediscache.conf"<<HFF
location ~ [^/]\.php(/|\$) {
  include /usr/local/nginx/conf/503include-only.conf;
    fastcgi_split_path_info ^(.+?\.php)(/.*)\$;
    if (!-f \$document_root\$fastcgi_script_name) {
        return 404;
    }

    set \$key "nginx-cache:\$scheme\$request_method\$host\$request_uri";
    srcache_fetch_skip \$skip_cache;
    srcache_store_skip \$skip_cache;
    srcache_response_cache_control off;
    set_escape_uri \$escaped_key \$key;
    srcache_fetch GET /redis-fetch \$key;
    srcache_store PUT /redis-store key=\$escaped_key;
    more_set_headers 'X-Cache \$srcache_fetch_status';
    more_set_headers 'X-Cache-2 \$srcache_store_status';

    fastcgi_pass   127.0.0.1:9000;
    #fastcgi_pass   unix:/var/run/php-fpm/php-fpm.sock;
    fastcgi_index  index.php;
    #fastcgi_param  SCRIPT_FILENAME  \$document_root\$fastcgi_script_name;
    fastcgi_param  SCRIPT_FILENAME    \$request_filename;
    #fastcgi_param PHP_ADMIN_VALUE open_basedir=\$document_root/:/usr/local/lib/php/:/tmp/;

# might shave 200+ ms off PHP requests
# which don't pass on a content length header
# slightly faster page response time at the
# expense of throughput / scalability
#sendfile on;
#tcp_nopush off;
#keepalive_requests 0;

fastcgi_connect_timeout 360s;
fastcgi_send_timeout 360s;
fastcgi_read_timeout 360s;
fastcgi_buffer_size 32k;
fastcgi_buffers 512 32k;
fastcgi_busy_buffers_size 1m;
fastcgi_temp_file_write_size 4m;
fastcgi_max_temp_file_size 4m;
fastcgi_intercept_errors off;

# next 3 lines when uncommented / enabled
# allow Nginx to handle uploads which then 
# passes back the completed upload to PHP
#fastcgi_pass_request_body off;
#client_body_in_file_only clean;
#fastcgi_param  REQUEST_BODY_FILE  \$request_body_file;

#new .04+ map method
fastcgi_param HTTPS \$server_https;

# comment out PATH_TRANSLATED line if /usr/local/lib/php.ini sets following:
# cgi.fix_pathinfo=0 
# as of centminmod v1.2.3-eva2000.01 default is set to cgi.fix_pathinfo=1

fastcgi_param  PATH_INFO          \$fastcgi_path_info;
fastcgi_param  PATH_TRANSLATED    \$document_root\$fastcgi_path_info;

fastcgi_param  QUERY_STRING       \$query_string;
fastcgi_param  REQUEST_METHOD     \$request_method;
fastcgi_param  CONTENT_TYPE       \$content_type;
fastcgi_param  CONTENT_LENGTH     \$content_length;

fastcgi_param  SCRIPT_NAME        \$fastcgi_script_name;
fastcgi_param  REQUEST_URI        \$request_uri;
fastcgi_param  DOCUMENT_URI       \$document_uri;
fastcgi_param  DOCUMENT_ROOT      \$document_root;
fastcgi_param  SERVER_PROTOCOL    \$server_protocol;
fastcgi_param  REQUEST_SCHEME     \$scheme;
fastcgi_param  HTTPS              \$https if_not_empty;
fastcgi_param  HTTP_PROXY         "";

fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
fastcgi_param  SERVER_SOFTWARE    nginx/\$nginx_version;

fastcgi_param  REMOTE_ADDR        \$remote_addr;
fastcgi_param  REMOTE_PORT        \$remote_port;
fastcgi_param  SERVER_ADDR        \$server_addr;
fastcgi_param  SERVER_PORT        \$server_port;
fastcgi_param  SERVER_NAME        \$server_name;

# Set php-fpm geoip variables
fastcgi_param GEOIP_COUNTRY_CODE \$geoip_country_code;
fastcgi_param GEOIP_COUNTRY_CODE3 \$geoip_country_code3;
fastcgi_param GEOIP_COUNTRY_NAME \$geoip_country_name;
fastcgi_param GEOIP_CITY_COUNTRY_CODE \$geoip_city_country_code;
fastcgi_param GEOIP_CITY_COUNTRY_CODE3 \$geoip_city_country_code3;
fastcgi_param GEOIP_CITY_COUNTRY_NAME \$geoip_city_country_name;
fastcgi_param GEOIP_REGION \$geoip_region;
fastcgi_param GEOIP_CITY \$geoip_city;
fastcgi_param GEOIP_POSTAL_CODE \$geoip_postal_code;
fastcgi_param GEOIP_CITY_CONTINENT_CODE \$geoip_city_continent_code;
fastcgi_param GEOIP_LATITUDE \$geoip_latitude;
fastcgi_param GEOIP_LONGITUDE \$geoip_longitude;

# PHP only, required if PHP was built with --enable-force-cgi-redirect
fastcgi_param  REDIRECT_STATUS    200;

                   }
HFF

cat > "/usr/local/nginx/conf/php-rediscache-shortttl.conf"<<HFI
location ~ [^/]\.php(/|\$) {
  include /usr/local/nginx/conf/503include-only.conf;
    fastcgi_split_path_info ^(.+?\.php)(/.*)\$;
    if (!-f \$document_root\$fastcgi_script_name) {
        return 404;
    }

    set \$key "nginx-cache:\$scheme\$request_method\$host\$request_uri";
    srcache_fetch_skip \$skip_cache;
    srcache_store_skip \$skip_cache;
    srcache_response_cache_control off;
    set_escape_uri \$escaped_key \$key;
    srcache_fetch GET /redis-fetch \$key;
    srcache_store PUT /redis-store-shortttl key=\$escaped_key;
    more_set_headers 'X-Cache \$srcache_fetch_status';
    more_set_headers 'X-Cache-2 \$srcache_store_status';

    fastcgi_pass   127.0.0.1:9000;
    #fastcgi_pass   unix:/var/run/php-fpm/php-fpm.sock;
    fastcgi_index  index.php;
    #fastcgi_param  SCRIPT_FILENAME  \$document_root\$fastcgi_script_name;
    fastcgi_param  SCRIPT_FILENAME    \$request_filename;
    #fastcgi_param PHP_ADMIN_VALUE open_basedir=\$document_root/:/usr/local/lib/php/:/tmp/;

# might shave 200+ ms off PHP requests
# which don't pass on a content length header
# slightly faster page response time at the
# expense of throughput / scalability
#sendfile on;
#tcp_nopush off;
#keepalive_requests 0;

fastcgi_connect_timeout 360s;
fastcgi_send_timeout 360s;
fastcgi_read_timeout 360s;
fastcgi_buffer_size 32k;
fastcgi_buffers 512 32k;
fastcgi_busy_buffers_size 1m;
fastcgi_temp_file_write_size 4m;
fastcgi_max_temp_file_size 4m;
fastcgi_intercept_errors off;

# next 3 lines when uncommented / enabled
# allow Nginx to handle uploads which then 
# passes back the completed upload to PHP
#fastcgi_pass_request_body off;
#client_body_in_file_only clean;
#fastcgi_param  REQUEST_BODY_FILE  \$request_body_file;

#new .04+ map method
fastcgi_param HTTPS \$server_https;

# comment out PATH_TRANSLATED line if /usr/local/lib/php.ini sets following:
# cgi.fix_pathinfo=0 
# as of centminmod v1.2.3-eva2000.01 default is set to cgi.fix_pathinfo=1

fastcgi_param  PATH_INFO          \$fastcgi_path_info;
fastcgi_param  PATH_TRANSLATED    \$document_root\$fastcgi_path_info;

fastcgi_param  QUERY_STRING       \$query_string;
fastcgi_param  REQUEST_METHOD     \$request_method;
fastcgi_param  CONTENT_TYPE       \$content_type;
fastcgi_param  CONTENT_LENGTH     \$content_length;

fastcgi_param  SCRIPT_NAME        \$fastcgi_script_name;
fastcgi_param  REQUEST_URI        \$request_uri;
fastcgi_param  DOCUMENT_URI       \$document_uri;
fastcgi_param  DOCUMENT_ROOT      \$document_root;
fastcgi_param  SERVER_PROTOCOL    \$server_protocol;
fastcgi_param  REQUEST_SCHEME     \$scheme;
fastcgi_param  HTTPS              \$https if_not_empty;
fastcgi_param  HTTP_PROXY         "";

fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
fastcgi_param  SERVER_SOFTWARE    nginx/\$nginx_version;

fastcgi_param  REMOTE_ADDR        \$remote_addr;
fastcgi_param  REMOTE_PORT        \$remote_port;
fastcgi_param  SERVER_ADDR        \$server_addr;
fastcgi_param  SERVER_PORT        \$server_port;
fastcgi_param  SERVER_NAME        \$server_name;

# Set php-fpm geoip variables
fastcgi_param GEOIP_COUNTRY_CODE \$geoip_country_code;
fastcgi_param GEOIP_COUNTRY_CODE3 \$geoip_country_code3;
fastcgi_param GEOIP_COUNTRY_NAME \$geoip_country_name;
fastcgi_param GEOIP_CITY_COUNTRY_CODE \$geoip_city_country_code;
fastcgi_param GEOIP_CITY_COUNTRY_CODE3 \$geoip_city_country_code3;
fastcgi_param GEOIP_CITY_COUNTRY_NAME \$geoip_city_country_name;
fastcgi_param GEOIP_REGION \$geoip_region;
fastcgi_param GEOIP_CITY \$geoip_city;
fastcgi_param GEOIP_POSTAL_CODE \$geoip_postal_code;
fastcgi_param GEOIP_CITY_CONTINENT_CODE \$geoip_city_continent_code;
fastcgi_param GEOIP_LATITUDE \$geoip_latitude;
fastcgi_param GEOIP_LONGITUDE \$geoip_longitude;

# PHP only, required if PHP was built with --enable-force-cgi-redirect
fastcgi_param  REDIRECT_STATUS    200;

                   }
HFI

################################################################################
# Setting up Nginx mapping

if [[ "$vhostssl" = [yY] ]] || [[ "$vhostssl" = 'le' ]] || [[ "$vhostssl" = 'led' ]] || [[ "$vhostssl" = 'lelive' ]] || [[ "$vhostssl" = 'lelived' ]]; then
  sslvhost
fi

if [ -f "${DIR_TMP}/openssl-${OPENSSL_VERSION}/configdata.pm" ]; then
  DETECTOPENSSL_ONEZERO=$(echo $OPENSSL_VERSION  | cut -d . -f1-2)
  DETECTOPENSSL_ONEONE=$(echo $OPENSSL_VERSION  | cut -d . -f1-3 | grep -o 1.1.1)
  if [[ "$DETECTOPENSSL_ONEZERO" = '1.1' ]] || [[ "$DETECTOPENSSL_ONEONE" = '1.1.1' ]]; then
      # openssl 1.1.0 unsupported flag enable-tlsext
      if [[ "$(grep -w 'tls1_3' "${DIR_TMP}/openssl-${OPENSSL_VERSION}/configdata.pm")" ]]; then
          TLSONETHREEOPT=' enable-tls1_3'
          TLSONETHREE_DETECT='y'
      else
          TLSONETHREEOPT=""
          TLSONETHREE_DETECT='n'
      fi
  fi
fi

if [[ "$TLSONETHREE_DETECT" = [yY] ]]; then
  TLSONETHREE_CIPHERS='TLS13-AES-128-GCM-SHA256:TLS13-AES-256-GCM-SHA384:TLS13-CHACHA20-POLY1305-SHA256:TLS13-AES-128-CCM-8-SHA256:TLS13-AES-128-CCM-SHA256:'
else
  TLSONETHREE_CIPHERS=""
fi

if [[ "$VHOST_PRESTATICINC" = [yY] ]]; then
  PRESTATIC_INCLUDES="include /usr/local/nginx/conf/pre-staticfiles-local-${vhostname}.conf;
  include /usr/local/nginx/conf/pre-staticfiles-global.conf;"
  touch "/usr/local/nginx/conf/pre-staticfiles-local-${vhostname}.conf"
  touch /usr/local/nginx/conf/pre-staticfiles-global.conf
else
  PRESTATIC_INCLUDES=""
fi

if [[ "$VHOST_CFAUTHORIGINPULL" = [yY] ]]; then
  CFAUTHORIGINPULL_INCLUDES="# cloudflare authenticated origin pull cert community.centminmod.com/threads/13847/
  #ssl_client_certificate /usr/local/nginx/conf/ssl/cloudflare/$vhostname/origin.crt;
  #ssl_verify_client on;"
else
  CFAUTHORIGINPULL_INCLUDES=""
fi

# main non-ssl vhost at yourdomain.com.conf for Wordpress
cat > "/usr/local/nginx/conf/conf.d/$vhostname.conf"<<ENSS
server {
  $DEDI_LISTEN
  server_name $vhostname www.$vhostname;

  #add_header X-Frame-Options SAMEORIGIN;
  add_header X-Xss-Protection "1; mode=block" always;
  add_header X-Content-Type-Options "nosniff" always;
  #add_header Referrer-Policy "strict-origin-when-cross-origin";
  #add_header Permissions-Policy "accelerometer=(), camera=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), payment=(), usb=()";

  # limit_conn limit_per_ip 16;
  # ssi  on;

  access_log /home/nginx/domains/$vhostname/log/access.log $NGX_LOGFORMAT buffer=256k flush=5m;
  error_log /home/nginx/domains/$vhostname/log/error.log;

  #include /usr/local/nginx/conf/autoprotect/$vhostname/autoprotect-$vhostname.conf;
  root /home/nginx/domains/$vhostname/public;
  # uncomment cloudflare.conf include if using cloudflare for
  # server and/or vhost site
  include /usr/local/nginx/conf/cloudflare.conf;
  #include /usr/local/nginx/conf/503include-main.conf;

  #include /usr/local/nginx/conf/wpincludes/${vhostname}/wpcacheenabler_${vhostname}.conf;
  #include /usr/local/nginx/conf/wpincludes/${vhostname}/wpsupercache_${vhostname}.conf;
  # https://community.centminmod.com/posts/18828/
  #include /usr/local/nginx/conf/wpincludes/${vhostname}/rediscache_${vhostname}.conf;  

  location /$wpsubdir_value {
  include /usr/local/nginx/conf/503include-only.conf;
  $SUBDIR_INCLUDE

  # Enables directory listings when index file not found
  #autoindex  on;

  # for wordpress super cache plugin
  #try_files /wp-content/cache/supercache/\$http_host/\$cache_uri/index.html \$uri \$uri/ ${WPSUBDIR}/index.php?q=\$uri&\$args;

  # for wp cache enabler plugin
  #try_files \$cache_enabler_uri_webp \$cache_enabler_uri \$uri \$uri/ \$custom_subdir/index.php?\$args;

  # Wordpress Permalinks
  #try_files \$uri \$uri/ ${WPSUBDIR}/index.php?q=\$uri&\$args;  

  # Nginx level redis Wordpress
  # https://community.centminmod.com/posts/18828/
  try_files \$uri \$uri/ ${WPSUBDIR}/index.php?\$args;

  }

location ~* ${WPSUBDIR}/(wp-login\.php) {
    limit_req zone=xwplogin burst=1 nodelay;
    #limit_conn xwpconlimit 30;
    auth_basic "Private";
    auth_basic_user_file /home/nginx/domains/$vhostname/htpasswd_wplogin;    
    include /usr/local/nginx/conf/php-wpsc.conf;
    # https://community.centminmod.com/posts/18828/
    #include /usr/local/nginx/conf/php-rediscache.conf;
}

location ~* ${WPSUBDIR}/(xmlrpc\.php) {
    limit_req zone=xwprpc burst=45 nodelay;
    #limit_conn xwpconlimit 30;
    include /usr/local/nginx/conf/php-wpsc.conf;
    # https://jetpack.com/support/hosting-faq/
    include /usr/local/nginx/conf/jetpack_whitelist_ip.conf;
    # https://community.centminmod.com/posts/18828/
    #include /usr/local/nginx/conf/php-rediscache.conf;
}

location ~* ${WPSUBDIR}/wp-admin/(load-scripts\.php) {
    limit_req zone=xwprpc burst=5 nodelay;
    #limit_conn xwpconlimit 30;
    include /usr/local/nginx/conf/php-wpsc.conf;
    # https://community.centminmod.com/posts/18828/
    #include /usr/local/nginx/conf/php-rediscache.conf;
}

location ~* ${WPSUBDIR}/wp-admin/(load-styles\.php) {
    limit_req zone=xwprpc burst=5 nodelay;
    #limit_conn xwpconlimit 30;
    include /usr/local/nginx/conf/php-wpsc.conf;
    # https://community.centminmod.com/posts/18828/
    #include /usr/local/nginx/conf/php-rediscache.conf;
}

  $NONSUBDIR_INCLUDE
  include /usr/local/nginx/conf/php-wpsc.conf;
  ${MULTIPHP_INCLUDES}
  # https://community.centminmod.com/posts/18828/
  #include /usr/local/nginx/conf/php-rediscache.conf;
  ${PRESTATIC_INCLUDES}
  include /usr/local/nginx/conf/staticfiles.conf;
  include /usr/local/nginx/conf/drop.conf;
  #include /usr/local/nginx/conf/errorpage.conf;
  include /usr/local/nginx/conf/vts_server.conf;
}
ENSS

# separate ssl vhost at yourdomain.com.ssl.conf
cat > "/usr/local/nginx/conf/conf.d/${vhostname}.ssl.conf"<<ESS
server {
  listen ${DEDI_IP}443 $LISTENOPT;
  server_name $vhostname www.$vhostname;

  ssl_certificate      /usr/local/nginx/conf/ssl/${vhostname}/${vhostname}.crt;
  ssl_certificate_key  /usr/local/nginx/conf/ssl/${vhostname}/${vhostname}.key;
  include /usr/local/nginx/conf/ssl_include.conf;

  $CFAUTHORIGINPULL_INCLUDES
  $HTTPTWO_MAXFIELDSIZE
  $HTTPTWO_MAXHEADERSIZE
  $HTTPTWO_MAXREQUESTS
  # mozilla recommended
  ssl_ciphers ${TLSONETHREE_CIPHERS}ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:${CHACHACIPHERS}DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA:ECDHE-ECDSA-DES-CBC3-SHA:ECDHE-RSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:DES-CBC3-SHA:!DSS;
  ssl_prefer_server_ciphers   on;
  $SPDY_HEADER

  # before enabling HSTS line below read centminmod.com/nginx_domain_dns_setup.html#hsts
  #add_header Strict-Transport-Security "max-age=31536000; includeSubdomains;";
  #add_header X-Frame-Options SAMEORIGIN;
  add_header X-Xss-Protection "1; mode=block" always;
  add_header X-Content-Type-Options "nosniff" always;
  #add_header Referrer-Policy "strict-origin-when-cross-origin";
  #add_header Permissions-Policy "accelerometer=(), camera=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), payment=(), usb=()";
  $COMP_HEADER;
  ssl_buffer_size 1369;
  ssl_session_tickets on;
  
  # enable ocsp stapling
  #resolver 8.8.8.8 8.8.4.4 1.1.1.1 1.0.0.1 valid=10m;
  #resolver_timeout 10s;
  #ssl_stapling on;
  #ssl_stapling_verify on;
  #ssl_trusted_certificate /usr/local/nginx/conf/ssl/${vhostname}/${vhostname}-trusted.crt;  

  # limit_conn limit_per_ip 16;
  # ssi  on;

  access_log /home/nginx/domains/$vhostname/log/access.log $NGX_LOGFORMAT buffer=256k flush=5m;
  error_log /home/nginx/domains/$vhostname/log/error.log;

  #include /usr/local/nginx/conf/autoprotect/$vhostname/autoprotect-$vhostname.conf;
  root /home/nginx/domains/$vhostname/public;
  # uncomment cloudflare.conf include if using cloudflare for
  # server and/or vhost site
  include /usr/local/nginx/conf/cloudflare.conf;
  include /usr/local/nginx/conf/503include-main.conf;

  #include /usr/local/nginx/conf/wpincludes/${vhostname}/wpcacheenabler_${vhostname}.conf;
  #include /usr/local/nginx/conf/wpincludes/${vhostname}/wpsupercache_${vhostname}.conf;
  # https://community.centminmod.com/posts/18828/
  #include /usr/local/nginx/conf/wpincludes/${vhostname}/rediscache_${vhostname}.conf;  

  location /$wpsubdir_value {
  include /usr/local/nginx/conf/503include-only.conf;
  $SUBDIR_INCLUDE

  # Enables directory listings when index file not found
  #autoindex  on;

  # for wordpress super cache plugin
  #try_files /wp-content/cache/supercache/\$http_host/\$cache_uri/index.html \$uri \$uri/ ${WPSUBDIR}/index.php?q=\$uri&\$args;

  # for wp cache enabler plugin
  #try_files \$cache_enabler_uri_webp \$cache_enabler_uri \$uri \$uri/ \$custom_subdir/index.php?\$args;  

  # Wordpress Permalinks
  #try_files \$uri \$uri/ ${WPSUBDIR}/index.php?q=\$uri&\$args; 

  # Nginx level redis Wordpress
  # https://community.centminmod.com/posts/18828/
  try_files \$uri \$uri/ ${WPSUBDIR}/index.php?\$args;

  }

location ~* ${WPSUBDIR}/(wp-login\.php) {
    limit_req zone=xwplogin burst=1 nodelay;
    #limit_conn xwpconlimit 30;
    auth_basic "Private";
    auth_basic_user_file /home/nginx/domains/$vhostname/htpasswd_wplogin;    
    include /usr/local/nginx/conf/php-wpsc.conf;
    ${MULTIPHP_INCLUDES}
    # https://community.centminmod.com/posts/18828/
    #include /usr/local/nginx/conf/php-rediscache.conf;
}

location ~* ${WPSUBDIR}/(xmlrpc\.php) {
    limit_req zone=xwprpc burst=45 nodelay;
    #limit_conn xwpconlimit 30;
    include /usr/local/nginx/conf/php-wpsc.conf;
    # https://jetpack.com/support/hosting-faq/
    include /usr/local/nginx/conf/jetpack_whitelist_ip.conf;
    ${MULTIPHP_INCLUDES}
    # https://community.centminmod.com/posts/18828/
    #include /usr/local/nginx/conf/php-rediscache.conf;
}

location ~* ${WPSUBDIR}/wp-admin/(load-scripts\.php) {
    limit_req zone=xwprpc burst=5 nodelay;
    #limit_conn xwpconlimit 30;
    include /usr/local/nginx/conf/php-wpsc.conf;
    ${MULTIPHP_INCLUDES}
    # https://community.centminmod.com/posts/18828/
    #include /usr/local/nginx/conf/php-rediscache.conf;
}

location ~* ${WPSUBDIR}/wp-admin/(load-styles\.php) {
    limit_req zone=xwprpc burst=5 nodelay;
    #limit_conn xwpconlimit 30;
    include /usr/local/nginx/conf/php-wpsc.conf;
    ${MULTIPHP_INCLUDES}
    # https://community.centminmod.com/posts/18828/
    #include /usr/local/nginx/conf/php-rediscache.conf;
}

  $NONSUBDIR_INCLUDE
  include /usr/local/nginx/conf/php-wpsc.conf;
  ${MULTIPHP_INCLUDES}
  # https://community.centminmod.com/posts/18828/
  #include /usr/local/nginx/conf/php-rediscache.conf;
  ${PRESTATIC_INCLUDES}
  include /usr/local/nginx/conf/staticfiles.conf;
  include /usr/local/nginx/conf/drop.conf;
  #include /usr/local/nginx/conf/errorpage.conf;
  include /usr/local/nginx/conf/vts_server.conf;
}
ESS

else

cat > "/usr/local/nginx/conf/conf.d/$vhostname.conf"<<END
server {
  $DEDI_LISTEN
  server_name $vhostname www.$vhostname;

  #add_header X-Frame-Options SAMEORIGIN;
  add_header X-Xss-Protection "1; mode=block" always;
  add_header X-Content-Type-Options "nosniff" always;
  #add_header Referrer-Policy "strict-origin-when-cross-origin";
  #add_header Permissions-Policy "accelerometer=(), camera=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), payment=(), usb=()";

  # limit_conn limit_per_ip 16;
  # ssi  on;

  access_log /home/nginx/domains/$vhostname/log/access.log $NGX_LOGFORMAT buffer=256k flush=5m;
  error_log /home/nginx/domains/$vhostname/log/error.log;

  #include /usr/local/nginx/conf/autoprotect/$vhostname/autoprotect-$vhostname.conf;
  root /home/nginx/domains/$vhostname/public;
  # uncomment cloudflare.conf include if using cloudflare for
  # server and/or vhost site
  include /usr/local/nginx/conf/cloudflare.conf;
  #include /usr/local/nginx/conf/503include-main.conf;

  #include /usr/local/nginx/conf/wpincludes/${vhostname}/wpcacheenabler_${vhostname}.conf;
  #include /usr/local/nginx/conf/wpincludes/${vhostname}/wpsupercache_${vhostname}.conf;
  # https://community.centminmod.com/posts/18828/
  #include /usr/local/nginx/conf/wpincludes/${vhostname}/rediscache_${vhostname}.conf;  

  location /$wpsubdir_value {
  include /usr/local/nginx/conf/503include-only.conf;
  $SUBDIR_INCLUDE

  # Enables directory listings when index file not found
  #autoindex  on;

  # for wordpress super cache plugin
  #try_files /wp-content/cache/supercache/\$http_host/\$cache_uri/index.html \$uri \$uri/ ${WPSUBDIR}/index.php?q=\$uri&\$args;

  # for wp cache enabler plugin
  #try_files \$cache_enabler_uri_webp \$cache_enabler_uri \$uri \$uri/ \$custom_subdir/index.php?\$args;   

  # Wordpress Permalinks
  #try_files \$uri \$uri/ ${WPSUBDIR}/index.php?q=\$uri&\$args; 

  # Nginx level redis Wordpress
  # https://community.centminmod.com/posts/18828/
  try_files \$uri \$uri/ ${WPSUBDIR}/index.php?\$args;

  }

location ~* ${WPSUBDIR}/(wp-login\.php) {
    limit_req zone=xwplogin burst=1 nodelay;
    #limit_conn xwpconlimit 30;
    auth_basic "Private";
    auth_basic_user_file /home/nginx/domains/$vhostname/htpasswd_wplogin;  
    include /usr/local/nginx/conf/php-wpsc.conf;
    ${MULTIPHP_INCLUDES}
    # https://community.centminmod.com/posts/18828/
    #include /usr/local/nginx/conf/php-rediscache.conf;
}

location ~* ${WPSUBDIR}/(xmlrpc\.php) {
    limit_req zone=xwprpc burst=45 nodelay;
    #limit_conn xwpconlimit 30;
    include /usr/local/nginx/conf/php-wpsc.conf;
    # https://jetpack.com/support/hosting-faq/
    include /usr/local/nginx/conf/jetpack_whitelist_ip.conf;
    ${MULTIPHP_INCLUDES}
    # https://community.centminmod.com/posts/18828/
    #include /usr/local/nginx/conf/php-rediscache.conf;
}

location ~* ${WPSUBDIR}/wp-admin/(load-scripts\.php) {
    limit_req zone=xwprpc burst=5 nodelay;
    #limit_conn xwpconlimit 30;
    include /usr/local/nginx/conf/php-wpsc.conf;
    ${MULTIPHP_INCLUDES}
    # https://community.centminmod.com/posts/18828/
    #include /usr/local/nginx/conf/php-rediscache.conf;
}

location ~* ${WPSUBDIR}/wp-admin/(load-styles\.php) {
    limit_req zone=xwprpc burst=5 nodelay;
    #limit_conn xwpconlimit 30;
    include /usr/local/nginx/conf/php-wpsc.conf;
    ${MULTIPHP_INCLUDES}
    # https://community.centminmod.com/posts/18828/
    #include /usr/local/nginx/conf/php-rediscache.conf;
}

  $NONSUBDIR_INCLUDE
  include /usr/local/nginx/conf/php-wpsc.conf;
  ${MULTIPHP_INCLUDES}
  # https://community.centminmod.com/posts/18828/
  #include /usr/local/nginx/conf/php-rediscache.conf;
  ${PRESTATIC_INCLUDES}
  include /usr/local/nginx/conf/staticfiles.conf;
  include /usr/local/nginx/conf/drop.conf;
  #include /usr/local/nginx/conf/errorpage.conf;
  include /usr/local/nginx/conf/vts_server.conf;
}
END

fi

touch "/usr/local/nginx/conf/wpincludes/${vhostname}/wpwhitelist_common.conf"
touch "/usr/local/nginx/conf/wpincludes/${vhostname}/wpsecure_${vhostname}_blacklist.conf"
touch "/usr/local/nginx/conf/wpincludes/${vhostname}/wpsecure_${vhostname}_whitelist.conf"

# Replace placeholders and write to target file
sed -e "s/\${vhostname}/${vhostname}/g" \
    /bigscoots/wpo/nginx/includes/bs_wp_whitelist_v2.conf > "/usr/local/nginx/conf/wpincludes/${vhostname}/wpsecure_${vhostname}.conf"

# WP super cache
cat > "/usr/local/nginx/conf/wpincludes/${vhostname}/wpsupercache_${vhostname}.conf" <<EFF
set \$cache_uri \$request_uri;

if (\$request_method = POST) { set \$cache_uri 'null cache'; }

if (\$query_string != "") { set \$cache_uri 'null cache'; }

if (\$request_uri ~* "/(\?add-to-cart=|\?wc-ajax=|\?wc-api=|cart/|my-account/|checkout/|shop/checkout/|store/checkout/|wp-json/|customer-dashboard/|addons/|wp-admin/.*|xmlrpc\.php|wp-.*\.php|index\.php|feed/|sitemap(_index)?\.xml|[a-z0-9_-]+-sitemap([0-9]+)?\.xml)") { set \$cache_uri 'null cache'; }

# bypass cache for woocommerce
if ( \$arg_add-to-cart != "" ) { set \$cache_uri 'null cache'; }
if ( \$arg_wc-api != "" ) { set \$cache_uri 'null cache'; }

## bypass cache for empty woocommerce carts
#if ( \$cookie_woocommerce_items_in_cart != "0" ) { set \$cache_uri 'null cache'; }

if (\$http_cookie ~* "comment_author|wordpress_[a-f0-9]+|wp-postpass|wordpress_logged_in|wc-api|edd_items_in_cart|woocommerce_items_in_cart|woocommerce_cart_hash|woocommerce_recently_viewed|wc_session_cookie_HASH|wp_woocommerce_session_|wptouch_switch_toggle") { set \$cache_uri 'null cache'; }
EFF

# for nginx level redis cache
cat > "/usr/local/nginx/conf/wpincludes/${vhostname}/rediscache_${vhostname}.conf" <<XFF
# Block nginx-help log from public viewing
location ~* ${WPSUBDIR}/wp-content/uploads/nginx-helper/ { deny all; }

set \$skip_cache 0;

# exclude mobile devices from redis caching
if (\$redis_device = mobile) { set \$skip_cache 1; }

# POST requests and urls with a query string should always go to PHP
if (\$request_method = POST) {
  set \$skip_cache 1;
}

if (\$query_string != "") {
  set \$skip_cache 1;
}

# Don't cache uris containing the following segments
if (\$request_uri ~* "\?add-to-cart=|\?wc-ajax=|\?wc-api=|/cart/|/my-account/|/checkout/|/shop/checkout/|/wp-json/|/store/checkout/|/customer-dashboard/|/addons/|/wp-admin/|/xmlrpc.php|wp-.*.php|/feed/|index.php|sitemap(_index)?.xml") {
  set \$skip_cache 1;
}

# Don't use the cache for logged in users or recent commenters
if (\$http_cookie ~* "comment_author|wordpress_[a-f0-9]+|wp-postpass|wordpress_no_cache|wordpress_logged_in|wc-api|edd_items_in_cart|woocommerce_items_in_cart|woocommerce_cart_hash|woocommerce_recently_viewed|wc_session_cookie_HASH|wp_woocommerce_session_|wptouch_switch_toggle") {
  set \$skip_cache 1;
}

# bypass cache for woocommerce
if (\$arg_add-to-cart != "") { set \$skip_cache 1; }
if (\$arg_wc-api != "") { set \$skip_cache 1; }

## bypass cache for empty woocommerce carts
#if (\$cookie_woocommerce_items_in_cart != "0") { 
#  set \$skip_cache 1;
#}

location /redis-fetch {
  internal  ;
  set  \$redis_key \$args;
  redis_pass  redisbackend;
  redis_connect_timeout 60000;
  redis_read_timeout 60000;
  redis_send_timeout 60000;
}

location /redis-store {
  internal  ;
  set_unescape_uri \$key \$arg_key ;
  redis2_query set \$key \$echo_request_body;
  redis2_query expire \$key 6h;
  redis2_pass  redisbackend;
  redis2_connect_timeout 60s;
  redis2_read_timeout 60s;
  redis2_send_timeout 60s;
}

location /redis-store-shortttl {
  internal  ;
  set_unescape_uri \$key \$arg_key ;
  redis2_query set \$key \$echo_request_body;
  redis2_query expire \$key 3600;
  redis2_pass  redisbackend;
  redis2_connect_timeout 60s;
  redis2_read_timeout 60s;
  redis2_send_timeout 60s;
}
XFF

cat > "/usr/local/nginx/conf/redisupstream.conf" <<GGG
map \$http_user_agent \$redis_device {
    default                                     'desktop';
    ~*(iPad|iPhone|Android|IEMobile|Blackberry) 'mobile';
    "~*Firefox.*Mobile"                         'mobile';
    "~*ipod.*mobile"                            'mobile';
    "~*Opera\ Mini"                             'mobile';
    "~*Opera\ Mobile"                           'mobile';
    "~*Mobile"                                  'mobile';
    "~*Tablet"                                  'mobile';
    "~*Kindle"                                  'mobile';
    "~*Windows\ Phone"                          'mobile';
}

upstream redisbackend {
  zone upstream_redis 64k;
  server 127.0.0.1:6379 weight=1 max_fails=3 fail_timeout=30s;
  #server 127.0.0.1:6380 weight=1 max_fails=3 fail_timeout=30s;
  #server 127.0.0.1:6381 weight=1 max_fails=3 fail_timeout=30s;
  #server 127.0.0.1:6382 weight=1 max_fails=3 fail_timeout=30s;
  #server 127.0.0.1:6383 weight=1 max_fails=3 fail_timeout=30s;
  #server 127.0.0.1:6384 weight=1 max_fails=3 fail_timeout=30s;

  #server 127.0.0.1:6380 backup;
  keepalive 4096;
}
GGG

REDISUPSTREAM_INCLUDECHECK=$(grep '\/usr\/local\/nginx\/conf\/redisupstream.conf' /usr/local/nginx/conf/nginx.conf)
  if [[ -z "$REDISUPSTREAM_INCLUDECHECK" ]]; then
    echo
    echo "include file /usr/local/nginx/conf/redisupstream.conf add to nginx.conf"
      sed -i 's|\/usr\/local\/nginx\/conf\/fastcgi_param_https_map.conf;|\/usr\/local\/nginx\/conf\/fastcgi_param_https_map.conf;\ninclude \/usr\/local\/nginx\/conf\/redisupstream.conf;|g' /usr/local/nginx/conf/nginx.conf
  fi

########### WP Super Cache Start ##############################
# only proceed in creating vhost if VHOSTNAME directory exist
if [[ -d "/home/nginx/domains/${vhostname}/public" ]]
then

  cd /home/nginx/domains/${vhostname}/public${WPSUBDIR}
  \wp core download --allow-root --skip-content
  \wp core config --dbname=$DB --dbuser=$DBUSER --dbpass=$DBPASS --allow-root
   
  NEWPREFIX=$(echo $RANDOM)
  sed -i "s/'wp_';/'${NEWPREFIX}_';/g" wp-config.php

  sed -i "/define( 'DB_COLLATE', '' );/ a\
  /** Enable core updates for minor releases (default) **/\ndefine('DISABLE_WP_CRON', false);\ndefine('WP_AUTO_UPDATE_CORE', 'minor' );\ndefine('WP_POST_REVISIONS', 10 );\ndefine('EMPTY_TRASH_DAYS', 10 );\ndefine('WP_CRON_LOCK_TIMEOUT', 60 );\ndefine('CONCATENATE_SCRIPTS', false);\
  " wp-config.php

  \wp core install --url=http://${vhostname}${WPSUBDIR} --title=${vhostname} --admin_email=${WPADMINEMAIL} --admin_password=${WPADMINPASS} --admin_name=${WPADMINUSER} --allow-root

  # change admin userid from 1 to a random 6 digit number
  # WP_PREFIX=$(wp eval 'echo $GLOBALS["table_prefix"];')
  WUID=$(echo $RANDOM$RANDOM |cut -c1-6)
  # \wp db query "UPDATE ${WP_PREFIX}wp_users SET ID=${WUID} WHERE ID=1; UPDATE ${WP_PREFIX}wp_usermeta SET user_id=${WUID} WHERE user_id=1" --allow-root
  \wp db query "UPDATE ${NEWPREFIX}_users SET ID=${WUID} WHERE ID=1; UPDATE ${NEWPREFIX}_usermeta SET user_id=${WUID} WHERE user_id=1" --allow-root

  if [[ "$setdisplayname" = [yY] ]]; then
    \wp user update ${WUID} --display_name=${WPADMIN_DISPLAYNAME} --allow-root
  fi

  # add index on autoload
  \wp db query "ALTER TABLE ${NEWPREFIX}_options ADD INDEX autoload_idx (autoload)" --allow-root

  # change permalinks out of the box
  \wp rewrite structure '/%post_id%/%postname%/' --allow-root

  cd /home/nginx/domains/${vhostname}/public${WPSUBDIR}

  # remove hello plugin
  \wp plugin uninstall hello --allow-root

  # allows user to add custom wp-cli commands after initiall install to
  # further customise their installation. you create a custom file at
  # /etc/centminmod/customwp_domain.com.inc where domain.com is the 
  # intended centmin.sh menu option 22 vhost site domain for your wp
  # installation. Then in that file add your wp-cli commands to the file
  # wrapped in a shell function named mywpcmds() { yourcode }. i.e. for
  # wp language install https://community.centminmod.com/posts/26045/
  # the below check will check for /etc/centminmod/customwp_domain.com.inc
  # file and then source include it into this routine and run the shell
  # function named mywpcmds which contains your custom wp-cli cmds that will
  # trigger and run
  if [ -f "${CONFIGSCANBASE}/customwp_${vhostname}.inc" ]; then
      # default is at /etc/centminmod/customwp_${vhostname}.inc
      source "${CONFIGSCANBASE}/customwp_${vhostname}.inc"
      mywpcmds
  fi

  chown -R nginx: /home/nginx/domains/${vhostname}/public &
  chmod 0770 wp-content
  chmod 0400 readme.html
  umask 022
fi
########### WP Super Cache End ##############################

cat > "/root/tools/wp_uninstall_${vhostname}.sh" <<END
#/bin/bash
echo "-------------------------------------------------------------------------"
echo "Do you want to uninstall/delete WP install for ${vhostname}"
echo "This will delete all data from /home/nginx/domains/${vhostname}"
echo "including any non-wordpress data installed at /home/nginx/domains/${vhostname}"
echo "This script will NOT delete the database, you will have to manually remove the"
echo "database named: $DB"
echo "Please backup your MySQL database called $DB before deleting"
echo "-------------------------------------------------------------------------"
read -ep "Uninstall WP Install For ${vhostname} [y/n]: " uninstall
echo
if [[ "\$uninstall" != [yY] ]]; then
  exit
fi

rm -rf /usr/local/nginx/conf/conf.d/${vhostname}.conf
rm -rf /usr/local/nginx/conf/conf.d/${vhostname}.ssl.conf
rm -rf /home/nginx/domains/${vhostname}
rm -rf /usr/local/nginx/conf/wpincludes/${vhostname}/wpsecure_${vhostname}.conf
rm -rf /usr/local/nginx/conf/wpincludes/${vhostname}/wpsupercache_${vhostname}.conf
rm -rf /root/tools/wp_updater_${vhostname}.sh
rm -rf /usr/local/nginx/conf/ssl/${vhostname}/${vhostname}.crt
rm -rf /usr/local/nginx/conf/ssl/${vhostname}/${vhostname}.key
rm -rf /usr/local/nginx/conf/ssl/${vhostname}/${vhostname}.csr
rm -rf /usr/local/nginx/conf/ssl/${vhostname}
rm -rf /usr/local/nginx/conf/wpincludes/${vhostname}/rediscache_${vhostname}.conf
rm -rf /usr/local/nginx/conf/wpincludes/${vhostname}/wpcacheenabler_${vhostname}.conf
rm -rf /root/.acme.sh/${vhostname}
crontab -l > cronjoblist
sed -i "/wp_updater_${vhostname}.sh/d" cronjoblist
sed -i "/\/${vhostname}\/wp-cron.php/d" cronjoblist
sed -i "/$vhostname cacheenabler cron/d" cronjoblist
crontab cronjoblist
rm -rf cronjoblist
pure-pw userdel $ftpuser >/dev/null 2>&1
service nginx restart
END

chmod 0700 /root/tools/wp_uninstall_${vhostname}.sh

  cecho "------------------------------------------------------------" $boldgreen
  cecho "Created wp_updater_${vhostname}.sh script" $boldyellow
  cecho "/root/tools/wp_updater_${vhostname}.sh" $boldyellow
  cecho "------------------------------------------------------------" $boldgreen


if [ -f "/usr/local/nginx/conf/wpincludes/$vhostname/emailfrom.ini" ]; then
  # SETWPADMINEMAIL_FROM=yourcustom-from-emailaddress
  . "/usr/local/nginx/conf/wpincludes/$vhostname/emailfrom.ini"
fi

if [[ "$SETWPADMINEMAIL_FROM" ]]; then
  WPADMINEMAIL_FROM="$SETWPADMINEMAIL_FROM"
else
  WPADMINEMAIL_FROM="$WPADMINEMAIL"
fi

cmservice nginx reload
echo
nginx -t
echo

cmservice php-fpm restart
if [[ "$PUREFTPD_DISABLED" = [nN] ]]; then
  cmservice pure-ftpd restart
fi

if [ -f /tmp/setupwp.log ]; then
  rm -rf /tmp/setupwp.log
fi

if [[ "$wpcli_ssldefault" = '1' ]]; then
  \wp option update home "https://${vhostname}${WPSUBDIR}"  --allow-root
  \wp option update siteurl "https://${vhostname}${WPSUBDIR}"  --allow-root
fi

{
echo 
if [[ "$PUREFTPD_DISABLED" = [nN] ]]; then
cecho "-------------------------------------------------------------" $boldyellow
echo "FTP hostname : $CNIP"
echo "FTP port : 21"
echo "FTP mode : FTP (explicit SSL)"
echo "FTP Passive (PASV) : ensure is checked/enabled"
echo "FTP username created for $vhostname : $ftpuser"
echo "FTP password created for $vhostname : $ftppass"
fi
cecho "-------------------------------------------------------------" $boldyellow
cecho "vhost for $vhostname created successfully" $boldwhite
echo
if [[ "$wpcli_ssldefault" != '1' ]]; then
  cecho "domain: http://$vhostname" $boldyellow
  cecho "vhost conf file for $vhostname created: /usr/local/nginx/conf/conf.d/$vhostname.conf" $boldwhite
fi
if [[ "$vhostssl" = [yY] ]] || [[ "$vhostssl" = 'le' ]] || [[ "$vhostssl" = 'led' ]] || [[ "$vhostssl" = 'lelive' ]] || [[ "$vhostssl" = 'lelived' ]]; then
  echo
  cecho "vhost ssl for $vhostname created successfully" $boldwhite
  echo
  cecho "domain: https://$vhostname" $boldyellow
  cecho "vhost ssl conf file for $vhostname created: /usr/local/nginx/conf/conf.d/${vhostname}.ssl.conf" $boldwhite
  cecho "/usr/local/nginx/conf/ssl_include.conf created" $boldwhite
  cecho "Self-signed SSL Certificate: /usr/local/nginx/conf/ssl/${vhostname}/${vhostname}.crt" $boldyellow
  cecho "SSL Private Key: /usr/local/nginx/conf/ssl/${vhostname}/${vhostname}.key" $boldyellow
  cecho "SSL CSR File: /usr/local/nginx/conf/ssl/${vhostname}/${vhostname}.csr" $boldyellow
  cecho "Backup SSL Private Key: /usr/local/nginx/conf/ssl/${vhostname}/${vhostname}-backup.key" $boldyellow
  cecho "Backup SSL CSR File: /usr/local/nginx/conf/ssl/${vhostname}/${vhostname}-backup.csr" $boldyellow  
  if [[ "$LETSENCRYPT_DETECT" = [yY] ]]; then
    cecho "letsdebug API check log: ${CENTMINLOGDIR}/letsdebug-${vhostname}-${DT}.log" $boldyellow
  fi
fi
echo
cecho "upload files to /home/nginx/domains/$vhostname/public" $boldwhite
cecho "vhost log files directory is /home/nginx/domains/$vhostname/log" $boldwhite
echo
cecho "------------------------------------------------------------" $boldgreen
cecho "SSH commands to uninstall created Wordpress install and Nginx vhost:" $boldyellow
cecho "  /root/tools/wp_uninstall_${vhostname}.sh" $boldyellow
cecho "------------------------------------------------------------" $boldgreen
echo
cecho "------------------------------------------------------------" $boldgreen
cecho "Wordpress Auto Updater created at:" $boldyellow
cecho "  /root/tools/wp_updater_${vhostname}.sh" $boldyellow
cecho "cronjob set for every 8 hours update (3x times per day)" $boldyellow
cecho "------------------------------------------------------------" $boldgreen
echo
cecho "Wordpress domain: $vhostname" $boldyellow
cecho "Wordpress DB Name: $DB" $boldyellow
cecho "Wordpress DB User: $DBUSER" $boldyellow
cecho "Wordpress DB Pass: $DBPASS" $boldyellow
cecho "Wordpress Admin User ID: ${WUID}" $boldyellow
cecho "Wordpress Admin User: $WPADMINUSER" $boldyellow
cecho "Wordpress Admin Pass: $WPADMINPASS" $boldyellow
cecho "Wordpress Admin Email: $WPADMINEMAIL" $boldyellow
if [[ "$setdisplayname" = [yY] ]]; then
  cecho "Wordpress Admin Display Name: $WPADMIN_DISPLAYNAME" $boldyellow
fi

if [[ "$disablepwdprotect" != [yY] ]]; then
  if [[ -f /usr/local/nginx/conf/htpasswd.sh && -f /home/nginx/domains/$vhostname/htpasswd_wplogin ]]; then
    echo  
    cecho "Wordpress wp-login.php password protection info:" $boldyellow
    cecho "wp-login.php protection file /home/nginx/domains/$vhostname/htpasswd_wplogin" $boldyellow
    cecho "wp-login.php protection Username: $HTUSER" $boldyellow
    cecho "wp-login.php protection Password: $HTPASS" $boldyellow
    if [[ "$wpcli_ssldefault" = '1' ]]; then
      cecho "https://${HTUSER}:${HTPASS}@${vhostname}${WPSUBDIR}/wp-login.php" $boldyellow
    else
      cecho "http://${HTUSER}:${HTPASS}@${vhostname}${WPSUBDIR}/wp-login.php" $boldyellow
    fi
    echo
    cecho "Resetting wp-login.php protection:" $boldyellow
    cecho "Step 1. remove protection file at /home/nginx/domains/$vhostname/htpasswd_wplogin" $boldyellow
    cecho "     rm -rf /home/nginx/domains/$vhostname/htpasswd_wplogin" $boldyellow
    cecho "Step 2. run command:" $boldyellow
    cecho "     /usr/local/nginx/conf/htpasswd.sh create /home/nginx/domains/$vhostname/htpasswd_wplogin YOURUSERNAME YOURPASSWORD" $boldyellow
    cecho "Step 3. restart Nginx + PHP-FPM services" $boldyellow
    cecho "     nprestart" $boldyellow
  fi
elif [[ "$disablepwdprotect" = [yY] ]]; then
    # disable wp-login.php password protection if user opts to do so
    sed -i "s|auth_basic \"Private\"|#auth_basic \"Private\"|" /usr/local/nginx/conf/conf.d/$vhostname.conf >/dev/null 2>&1
    sed -i "s|auth_basic_user_file \/home\/nginx\/domains\/$vhostname\/htpasswd_wplogin|#auth_basic_user_file \/home\/nginx\/domains\/$vhostname\/htpasswd_wplogin|" /usr/local/nginx/conf/conf.d/$vhostname.conf >/dev/null 2>&1
    if [[ "$vhostssl" = [yY] ]] || [[ "$vhostssl" = 'le' ]] || [[ "$vhostssl" = 'led' ]] || [[ "$vhostssl" = 'lelive' ]] || [[ "$vhostssl" = 'lelived' ]]; then
      sed -i "s|auth_basic \"Private\"|#auth_basic \"Private\"|" /usr/local/nginx/conf/conf.d/$vhostname.ssl.conf >/dev/null 2>&1
      sed -i "s|auth_basic_user_file \/home\/nginx\/domains\/$vhostname\/htpasswd_wplogin|#auth_basic_user_file \/home\/nginx\/domains\/$vhostname\/htpasswd_wplogin|" /usr/local/nginx/conf/conf.d/$vhostname.ssl.conf >/dev/null 2>&1
    fi
    service nginx reload
fi

} 2>&1 | tee /tmp/setupwp.log

if [ -f "/usr/local/nginx/conf/conf.d/${vhostname}.ssl.conf" ]; then
  sed -i "s|^  #include \/usr\/local\/nginx\/conf\/cloudflare.conf;|  include \/usr\/local\/nginx\/conf\/cloudflare.conf;|g" "/usr/local/nginx/conf/conf.d/${vhostname}.ssl.conf"
fi

# whether autoprotect-$vhostname.conf include file is uncommented (enabled) or commented out (disabled)
if [[ "$VHOSTCTRL_AUTOPROTECTINC" = [nN] ]]; then
  if [ -f "/usr/local/nginx/conf/autoprotect/$vhostname/autoprotect-$vhostname.conf" ]; then
    if [ -f "/usr/local/nginx/conf/conf.d/$vhostname.conf" ]; then
      sed -i "s|^  include \/usr\/local\/nginx\/conf\/autoprotect\/$vhostname\/autoprotect-$vhostname.conf;|  #include \/usr\/local\/nginx\/conf\/autoprotect\/$vhostname\/autoprotect-$vhostname.conf;|g" "/usr/local/nginx/conf/autoprotect/$vhostname/autoprotect-$vhostname.conf"
    fi
    if [ -f "/usr/local/nginx/conf/conf.d/${vhostname}.ssl.conf" ]; then
      sed -i "s|^  include \/usr\/local\/nginx\/conf\/autoprotect\/$vhostname\/autoprotect-$vhostname.conf;|  #include \/usr\/local\/nginx\/conf\/autoprotect\/$vhostname\/autoprotect-$vhostname.conf;|g" "/usr/local/nginx/conf/conf.d/${vhostname}.ssl.conf"
    fi
  fi
fi

# make sure all wordpress installed files are owned by nginx user/group
chown -R nginx:nginx /home/nginx/domains/${vhostname}/public &

if [[ -f "${CENTMINLOGDIR}/centminmod_${SCRIPT_VERSION}_${DT}_wordpress_addvhost.log" ]]; then
  # populate plain text logs for QR Code generation
  touch "${CENTMINLOGDIR}/centminmod_${SCRIPT_VERSION}_${DT}_wordpress_addvhost_${vhostname}-logins.log"  
if [[ "$PUREFTPD_DISABLED" = [nN] ]]; then
  touch "${CENTMINLOGDIR}/centminmod_${SCRIPT_VERSION}_${DT}_wordpress_addvhost_${vhostname}-logins-ftp.log"
cat >> "${CENTMINLOGDIR}/centminmod_${SCRIPT_VERSION}_${DT}_wordpress_addvhost_${vhostname}-logins-ftp.log" <<EOF
FTP hostname: $CNIP
FTP port: 21
FTP mode: FTP (explicit SSL)
FTP Passive (PASV): ensure is checked/enabled
FTP username: $ftpuser
FTP password: $ftppass
EOF
fi
cat >> "${CENTMINLOGDIR}/centminmod_${SCRIPT_VERSION}_${DT}_wordpress_addvhost_${vhostname}-logins.log" <<EOF
Wordpress Info
domain: $vhostname
DB Name: $DB
DB User: $DBUSER
DB Pass: $DBPASS
Admin User: $WPADMINUSER
Admin Pass: $WPADMINPASS
Admin Email: $WPADMINEMAIL
EOF
if [[ "$setdisplayname" = [yY] ]]; then
cat >> "${CENTMINLOGDIR}/centminmod_${SCRIPT_VERSION}_${DT}_wordpress_addvhost_${vhostname}-logins.log" <<EOF
Wordpress Admin Display Name: $WPADMIN_DISPLAYNAME
EOF
fi

else

  echo ""
  cecho "-------------------------------------------------------------" $boldyellow
  cecho "vhost for $vhostname already exists" $boldwhite
  cecho "/home/nginx/domains/$vhostname already exists" $boldwhite
  cecho "-------------------------------------------------------------" $boldyellow
  echo ""

fi
}