#!/bin/bash

comment_out=false

# Parse command-line arguments
while getopts ":c" opt; do
  case $opt in
    c)
      comment_out=true
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      exit 1
      ;;
  esac
done

# Loop through each directory in /home
for dir in /home/*; do
  if [ -d "$dir/public_html" ]; then
    htaccess_file="$dir/public_html/.htaccess"
    wp_config_file="$dir/public_html/wp-config.php"

    if [ -f "$htaccess_file" ]; then
      # Find lines containing "Trusted" followed by an IP address, excluding commented lines
      trusted_matches=$(grep -E '^[^#]*Trusted\s+[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+' "$htaccess_file")

      # Find lines containing "RewriteCond %{HTTP_USER" missing the closing brace
      http_user_matches=$(grep -E '^[^#]*RewriteCond %{HTTP_USER[^}]*$' "$htaccess_file")

      if [ -n "$trusted_matches" ] || [ -n "$http_user_matches" ]; then
        echo "Found matching lines in $htaccess_file"
        echo "$trusted_matches"
        echo "$http_user_matches"

        if [ "$comment_out" = true ]; then
          echo "Commenting out matching lines in $htaccess_file"

          # Comment out matching Trusted lines
          sed -i.bak -E 's/^([^#]*Trusted\s+[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)/#\1/' "$htaccess_file"

          # Comment out matching RewriteCond lines
          sed -i.bak -E 's/^(.*RewriteCond \%\{HTTP_USER[^}]*$)/#\1/' "$htaccess_file"
        fi
      fi
    fi

    if [ -f "$wp_config_file" ]; then
      # Check if the line "define('WP_MEMORY_LIMIT', '1024M');" exists
      memory_limit_line=$(grep -F "define('WP_MEMORY_LIMIT', '1024M');" "$wp_config_file")

      if [ -z "$memory_limit_line" ]; then
        echo "Adding WP_MEMORY_LIMIT definition to $wp_config_file"
        echo "define('WP_MEMORY_LIMIT', '1024M');" >> "$wp_config_file"
      fi
    fi
  fi
done
