#!/bin/bash
# info: change user shell
# options: USER SHELL
#
# example: v-change-user-shell admin nologin
#
# This function changes system shell of a user. Shell gives ability to use ssh.

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

# Argument definition
user=$1
shell=$2

# 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
# shellcheck source=/usr/local/hestia/conf/hestia.conf
source $HESTIA/conf/hestia.conf

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

check_args '2' "$#" 'USER SHELL'
is_format_valid 'user' 'shell'
is_object_valid 'user' 'USER' "$user"
is_object_unsuspended 'user' 'USER' "$user"

# Perform verification if read-only mode is enabled
check_hestia_demo_mode

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

# Get shell full path
shell_path=$(grep -w "$shell" /etc/shells | head -n1)

# Changing passwd file
/usr/bin/chsh -s "$shell_path" "$user" > /dev/null 2>&1
shell=$(basename "$shell_path")

# Adding jailed sftp env
if [[ "$shell" =~ nologin ]] || [[ "$shell" =~ rssh ]]; then
	$BIN/v-add-user-sftp-jail "$user" > /dev/null 2>&1
else
	$BIN/v-delete-user-sftp-jail "$user" > /dev/null 2>&1
fi

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

# Changing user shell
update_user_value "$user" '$SHELL' "$shell"

# Logging
$BIN/v-log-action "system" "Info" "System" "User SSH shell changed (Shell: $shell, User: $user)."
log_event "$OK" "$ARGUMENTS"

exit