#!/bin/sh
#
# @license   http://www.gnu.org/licenses/gpl.html GPL Version 3
# @author    Volker Theile <volker.theile@openmediavault.org>
# @author    OpenMediaVault Plugin Developers <plugins@omv-extras.org>
# @copyright Copyright (c) 2009-2013 Volker Theile
# @copyright Copyright (c) 2013-2026 openmediavault plugin developers
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

if [ $# -ne 3 ]; then
  echo "Wrong number of arguments passed."
  echo "${0} [path] [dirperms] [clearacls]"
  exit 1
fi

# logging location
logDir="/var/log"
logFile="${logDir}/omv-resetperms.log"

_log() {
  msg="${1}"
  printf '[%s] [resetperms] %s\n' "$(date +'%Y-%m-%d %H:%M:%S%z')" "${msg}" | tee -a "${logFile}" >&2
}

. /etc/default/openmediavault

export LC_ALL=C

usergrp=${OMV_USERMGMT_DEFAULT_GROUP:-users}

path="${1}"
dirperms="${2}"
clearacl="${3}"

if [ ! -d "${path}" ]; then
  _log "ERROR: path is not a directory: ${path}"
  exit 2
fi

case "${dirperms}" in
  700) fileperms=600 ;;
  750) fileperms=640 ;;
  770) fileperms=660 ;;
  755) fileperms=644 ;;
  775) fileperms=664 ;;
  777) fileperms=666 ;;
  *)   fileperms=644 ;;
esac

_log "path :: ${path}"
_log "dir perms :: ${dirperms}"
_log "file perms :: ${fileperms}"
_log "clear acls :: ${clearacl}"
_log "user group :: ${usergrp}"

# Clear ACLs
if [ "${clearacl}" = "1" ]; then
  _log "Clearing ACLs ..."
  setfacl -Rb "${path}"
  _log "ACLs cleared."
fi

# Ownership: only touch items not already root:usergrp
_log "Changing owner to root:${usergrp} ..."
find "${path}" \( ! -user root -o ! -group "${usergrp}" \) -exec chown root:"${usergrp}" {} +
_log "Ownership reset."

# Directory perms: only touch directories whose mode differs (exact match)
_log "Change directory permissions to ${dirperms} ..."
find "${path}" -type d ! -perm "${dirperms}" -exec chmod "${dirperms}" {} +
_log "Directory permissions reset."

# File perms: only touch files whose mode differs (exact match)
_log "Change file permissions to ${fileperms} ..."
find "${path}" -type f ! -perm "${fileperms}" -exec chmod "${fileperms}" {} +
_log "File permissions reset."

_log "Reset complete."

exit 0
