#!/bin/bash

# info:
# This script will fix files permissions for desired user (if ownership is lost or files have wrong chmod)

# options: user

#----------------------------------------------------------#
#                    Variable&Function                     #
#----------------------------------------------------------#

whoami=$(whoami)
if [ "$whoami" != "root" ] && [ "$whoami" != "admin" ] ; then
    echo "You must be root or admin to execute this script";
    exit 1;
fi

# Argument definition
user=$1

# Includes
source $VESTA/func/main.sh

#----------------------------------------------------------#
#                    Verifications                         #
#----------------------------------------------------------#

check_args '1' "$#" 'USER'
is_format_valid 'user'
is_object_valid 'user' 'USER' "$user"

#----------------------------------------------------------#
#                       Action                             #
#----------------------------------------------------------#

find /home/$user/conf/mail/ -type d -exec chown Debian-exim:mail {} \;
find /home/$user/conf/mail/*/ -type f -exec chown Debian-exim:mail {} \;
find /home/$user/conf/mail/*/ -name "passwd" -type f -exec chown dovecot:mail {} \;

find /home/$user/mail/ -type d -exec chown $user:mail {} \;
find /home/$user/mail/*/ -type d -exec chown $user:mail {} \;
find /home/$user/mail/*/ -type f -exec chown $user:mail {} \;
find /home/$user/mail/*/ -type d -exec chmod u+rwx {} \;
find /home/$user/mail/*/ -type d -exec chmod g+rwx {} \;
find /home/$user/mail/*/ -type f -exec chmod u+rw {} \;
find /home/$user/mail/*/ -type f -exec chmod g+rw {} \;
find /home/$user/mail/*/ -maxdepth 1 -type d -exec chmod g-rwx {} \;

find /home/$user/conf/dns/ -type f -exec chown root:bind {} \;
find /home/$user/conf/ -type d -exec chown root:root {} \;

find /home/$user/web/*/public_html/ -type d -exec chmod 755 {} +
find /home/$user/web/*/public_html/ -type f -exec chmod 644 {} +
find /home/$user/web/*/public_html/ -exec chown $user:$user {} \;

echo "Done, permissions fixed for user: $user"

# Logging
log_event "$OK" "$ARGUMENTS"

exit