#!/bin/bash

# Thanks to https://gist.github.com/GreenSkunk/c19b450a6060c8e6e59877a6b1e5f7a8/

path=${1%/}
user=${2}
group=${2}

if [ -z "${path}" ] || [ ! -d "${path}/sites" ] || [ ! -f "${path}/core/core.api.php" ]; then
  path=$(pwd)      
fi

if [ -z "${user}" ] || [ "`id -un ${user} 2> /dev/null`" != "${user}" ]; then
  user=$(whoami)
  group=$(whoami)
fi

cd $path;

echo -e "Changing ownership of all contents of "$(pwd)" :\n user => "${user}" \t group => "${group}"\n"
chown -R ${user}:${group} .
echo "Changing permissions of all directories inside "${path}" to "755"..."
find . -type d -exec chmod u=rwx,go=rx {} \;
echo -e "Changing permissions of all files inside "${path}" to "644"...n"
find . -type f -exec chmod u=rw,go=r {} \;

cd sites;

echo "Changing permissions of "files" directories in "${path}/sites" to "775"..."
find . -type d -name files -exec chmod ug=rwx,o=rx '{}' \;
echo "Changing permissions of all files inside all "files" directories in "${path}/sites" to "664"..."
find . -name files -type d -exec find '{}' -type f \; | while read FILE; do chmod ug=rw,o=r "$FILE"; done
echo "Changing permissions of all directories inside all "files" directories in "${path}/sites" to "775"..."
find . -name files -type d -exec find '{}' -type d \; | while read DIR; do chmod ug=rwx,o=rx "$DIR"; done

echo "Changing permissions of "files" directory to "777"..."
find . -type d -name files -exec chmod -R ugo=rwx '{}' \;

cd ..;
echo "Setting scripts in root drupal directory as executable..."
find . -type f -name "*.sh" -exec chmod +x '{}' \;

