#!/bin/bash
# info: delete user sftp jail
# options: USER
#
# example: v-delete-user-sftp-jail whistler
#
# This function disables sftp jailed environment for USER

#----------------------------------------------------------#
#                Variables & Functions                     #
#----------------------------------------------------------#

# Argument definition
user=$1

# Includes
# shellcheck source=/etc/hestiacp/hestia.conf
source /etc/hestiacp/hestia.conf
# shellcheck source=/usr/local/hestia/func/main.sh
source $HESTIA/func/main.sh
# load config file
source_conf "$HESTIA/conf/hestia.conf"

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

check_args '1' "$#" 'USER'
is_format_valid 'user'
user_str=$(grep "^$user:" /etc/passwd)
if [ -z "$user_str" ]; 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"

match_string="$ssh_users,"
# Check if jail exist
if [[ ! "$match_string" =~ ,$user, ]]; then
	exit 2
fi

# Perform verification if read-only mode is enabled
check_hestia_demo_mode

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

# Remove user from array
for sftp_user in "${users[@]}"; do
	if [ "$sftp_user" != "$user" ]; then
		new_users+=($sftp_user)
	fi
done

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

# chown permissions back to user:user
if [ -d "/home/$user" ]; then
	chown $user:$user /home/$user
fi
#----------------------------------------------------------#
#                       Hestia                             #
#----------------------------------------------------------#

# Restart ssh service
service ssh restart > /dev/null 2>&1
service sshd restart > /dev/null 2>&1

# Logging
log_event "$OK" "$ARGUMENTS"

exit
