#!/bin/bash

# The global directory where to start searching from, change this to your directory
GLOBAL_DIR="/home/bjaskulski/Repos/full-gitlab/wpdesk"

# The string to search for in the composer dependency key
SEARCH_DEP="plugin-flow"

# Stores projects with and without the dependency
DEP_ADDED=()
DEP_NOT_ADDED=()

# Export SEARCH_DEP for it to be accessible in the jq environment
export SEARCH_DEP

# Function to display a simple progress bar
function show_progress_bar() {
  local progress=$(( $1 * 100 / $2 ))
  printf "["

  local filled=$((progress / 2))
  for (( i = 0; i < filled; i++ )); do printf "="; done

  if [ $((progress % 2)) -eq 1 ]; then printf ">"; fi

  for (( i = filled + 1; i < 50; i++ )); do printf " "; done
  printf "] %d%%\r" "$progress"
}

# Function to display colored headers
function display_header() {
  color='\033[1;34m' # Blue color
  reset='\033[0m'    # Reset color
  echo -e "${color}$1${reset}"
}

  # Checks if a directory contains a WP plugin
function is_wp_plugin_dir() {
    local dir="$1"

    # Use 'fd' to search for PHP files in the same directory and check if 'Plugin Name:' is present
    if fd . --max-depth 1 --type f -e php "$dir" -x grep "Plugin Name:" {} | grep -qm 1 .; then
        return 0 # It's a plugin directory
    fi

    return 1 # Not a plugin directory
}


total_files=$(fd 'composer.json' "$GLOBAL_DIR" | wc -l)
current_file=0

# Traverse the directory hierarchy
while IFS= read -r -d '' composer_file; do
  dir=$(dirname "$composer_file")
  rel_path=$(dirname "$(realpath --relative-to="$GLOBAL_DIR" "$composer_file")")

  show_progress_bar $((++current_file)) "$total_files"

  if ! is_wp_plugin_dir "$dir"; then
    # Skip non-plugin directories
    continue
  fi

    # Check if the composer.json has the dependency
    if jq -e --arg dep "$SEARCH_DEP" '.["require-dev"] | to_entries[] | select(.key | test($dep))' "$composer_file" &> /dev/null; then
      # If the dependency is found
      DEP_ADDED+=("$rel_path")
    else
      # If the dependency is not found
      DEP_NOT_ADDED+=("$rel_path")
      fi
    done < <(fd --relative-path -0 composer.json "$GLOBAL_DIR")

# Clear progress bar line
printf "\033[2K"

# Output the results with colored headers
display_header "Projects with the dependency '$SEARCH_DEP':"
printf "%s\n" "${DEP_ADDED[@]}"

display_header "Projects without the dependency '$SEARCH_DEP':"
printf "%s\n" "${DEP_NOT_ADDED[@]}"

# Summary
total_projects=$(( ${#DEP_ADDED[@]} + ${#DEP_NOT_ADDED[@]} ))
echo -e "\nTotal projects: $total_projects"
echo -e "Projects with the dependency '$SEARCH_DEP': ${#DEP_ADDED[@]}"
echo -e "Projects without the dependency '$SEARCH_DEP': ${#DEP_NOT_ADDED[@]}"