#!/bin/bash

# Set Valet sites directory
sites_directory="$HOME/pmc/sites"

# Set the Nginx server block directory to iterate through
server_block_directory="$HOME/.config/valet/Nginx"

# Set Valet's current top-level domain
gltd="test"

# FastCGI buffers
fastcgi_buffers_number="16"
fastcgi_buffers_size="16k"
fascgi_buffer_size="32k"

# Loop through each Nginx server block file
for file in $server_block_directory/*;
do
	# Check if the file is a server block file
	if [[ $file == *.$gltd ]]
	then
		site=$(basename $file)
		site="${site%.*}"

		# Check if the file already contains our injections.
		if ! grep -q "# ADDED BY PMC:" $file; then
			echo "Updating ${site}"
			sed -i '' 's~http2_push_preload on;~http2_push_preload on;\n\
    # ADDED BY PMC: Enable concat scripts\/styles (per https:\/\/github.com\/Automattic\/nginx-http-concat#installation--configuration)\
    location \/_static\/ {\
        fastcgi_pass \"unix:'$HOME'\/.config\/valet\/valet.sock\";\
        fastcgi_index \"'$HOME'/.composer/vendor/laravel/valet/server.php\";\
        include fastcgi_params;\
        fastcgi_param SCRIPT_FILENAME '$sites_directory'\/'$site'\/wp-content\/mu-plugins\/http-concat\/ngx-http-concat.php;\
    }\
\
    # ADDED BY PMC: Increase buffer size for larger requests (like in editor)\
    fastcgi_buffers '$fastcgi_buffers_number' '$fastcgi_buffers_size';\
    fastcgi_buffer_size '$fascgi_buffer_size';~' $file
		fi
	fi
done

valet restart nginx
