#!/bin/bash
# info: add user sftp jail
# options: USER [RESTART]
#
# The script enables sftp jailed environment


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

# Argument definition
user=$1
restart=$2

# Includes
source $HESTIA/func/main.sh
source $HESTIA/conf/hestia.conf


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

check_args '1' "$#" 'USER'
is_format_valid 'user'
user_str=$(grep "^$user:" /etc/passwd |egrep "rssh|nologin")
if [ -z "$user_str" ]; then
    exit
fi

# Do not create chroot for syslog user
if [ $user = "syslog" ]; then
    exit
fi

# Get current users and split into array
ssh_users=$(grep -A1 "^# Hestia SFTP Chroot" /etc/ssh/sshd_config | sed -n 2p | sed 's/Match User //')
IFS=',' read -r -a users <<< "$ssh_users"

# Check if jail is already enabled
if [[ " ${users[@]} " =~ " ${user} " ]]; then
    if [[ -d /home/$user && ! -n "$(find /home/$user -user root -print -prune -o -prune)" ]]; then
       chown root:root /home/$user
    fi
    exit;
fi

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

# Add user to array
users+=($user)

# Write new user list to config
users=$(IFS=',';echo "${users[*]// /|}";IFS=$' \t\n')
sed -i "s/$ssh_users/$users/g" /etc/ssh/sshd_config

# Set home folder permission to root
if [ -d "/home/$user" ]; then
    chown root:root /home/$user
fi

#----------------------------------------------------------#
#                       Hestia                             #
#----------------------------------------------------------#

# Restart ssh service
if [ "$restart" = 'no' ]; then
    # Skip restart of SSH daemon
    echo "" > /dev/null 2>&1
else
    service ssh restart > /dev/null 2>&1
fi

# Logging
log_event "$OK" "$ARGUMENTS"

exit
