#!/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 {
  if [ -e "$1" ] ; then
    owner=nobody
    group=users
    if [ $# -ge 2 ]; then
      owner=$2
    fi
    if [ $# -ge 3 ]; then
      group=$3
    fi
    echo processing "$1"
    echo ... chmod -R u-x,go-rwx,go+u,ugo+X "$1"
    chmod -R u-x,go-rwx,go+u,ugo+X "$1"
    echo ... chown -R $owner:$group "$1"
    chown -R $owner:$group "$1"
    echo ... sync
    sync
  fi
}

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

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