#!/bin/bash

# Usage: newperms [dir] [owner] [group]
# Recursively changes the ownership and permissions of the directory and all files/subdirs
# within the directory.
# If no arguments given, operates on /mnt/cache and /mnt/disk*, setting owner:group to nobody:users
# default owner is 'nobody', default group is 'users'

# This was created to fix ownership/permissions when upgrading to unRAID version 5.

# With corrections suggested by forum member Stokkes

# Here's a breakdown of chmod "u-x,go-rwx,go+u,ugo+X"
#  u-x     Clear the 'x' bit in the user permissions (leaves rw as-is)
#  go-rwx  Clear the 'rwx' bits in both the group and other permissions
#  go+u    Copy the user permissions to group and other
#  ugo+X   Set the 'x' bit for directories in user, group, and other

function process {
  list="$1"
  [[ $# -ge 2 ]] && owner=$2 || owner=nobody
  [[ $# -ge 3 ]] && group=$3 || group=users
  ifs=$IFS; IFS='|'
  for dir in $list; do
    echo "$dir"
    if [[ -d $dir ]]; then
      echo processing "$dir"
      echo ... chmod -R u-x,go-rwx,go+u,ugo+X "$dir"
      chmod -R u-x,go-rwx,go+u,ugo+X "$dir"
      echo ... chown -R $owner:$group "$dir"
      chown -R $owner:$group "$dir"
      echo ... sync
      sync
    fi
  done
  IFS=$ifs
}

if [[ -n $1 ]]; then
  process "$@"
else
  process /mnt/cache
  for disk in /mnt/disk[0-9]*; do
    process $disk
  done
fi

echo
secs=$SECONDS
printf "completed, elapsed time: %.2d:%.2d:%.2d\n" $(($secs/3600)) $(($secs%3600/60)) $(($secs%60))
