#!/bin/bash

set -e

die() { echo "$1"; exit 1; }

[[ -n "$1" ]] || die 'No directory provided'
DIR="$1"

# Check if directory exists
[[ -d "$DIR" ]] || die "Directory $DIR does not exist"

# Find all JSON files in the directory and process them
find "$DIR" -type f -name "*.json" | while read -r config_file; do
  echo "Processing config file: $config_file"
  
  # Read and parse commands.json using jq
  jq -c '.[]' "$config_file" | while read -r line; do
    command=$(jq -r '.command' <<< "$line")
    file_list=$(jq -r '.file_list[]' <<< "$line")
    
    # Get exclude list if it exists (will be empty array if not present)
    exclude_list=$(jq -r '.exclude_file_list[]? // empty' <<< "$line")

    # Execute the command on each file in file_list
    for file in $file_list; do
      # Check if this command has recursive flag and exclusions
      if [[ "$command" == *"-R"* ]] && [[ -n "$exclude_list" ]]; then
        echo "Processing $file with exclusions: $exclude_list"
        
        # Build exclusion paths for find command
        exclusion_paths=""
        for exclude_file in $exclude_list; do
          if [[ -z "$exclusion_paths" ]]; then
            exclusion_paths="-path $exclude_file"
          else
            exclusion_paths="$exclusion_paths -o -path $exclude_file"
          fi
        done
        
        # Remove -R from the original command
        base_command=$(echo "$command" | sed 's/-R\([a-zA-Z]*\)/-\1/g' | sed 's/--recursive//g')
        
        # Build and execute find command
        find_cmd="find $file \\( $exclusion_paths \\) -prune -o -exec $base_command {} +"
        echo "Executing: $find_cmd"
        eval "$find_cmd" || true
      else
        # Original behavior for non-recursive commands or commands without exclusions
        eval "$command $file" || true
      fi
    done
  done
done