#!/bin/bash
# info: add php  version alias to .bash_aliases
# options: USER VERSION
#
# example: v-change-user-php-cli user 7.4
#
# add line to .bash_aliases to set default php command line
# version when multi-php is enabled.

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

# Argument definition
user=$1
version=$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
# load config file
source_conf "$HESTIA/conf/hestia.conf"

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

if [ -f /etc/redhat-release ];then
	FILE=$HOMEDIR/$user/.bashrc.d/bash_aliases
else
	FILE=$HOMEDIR/$user/.bash_aliases
fi

check_args '2' "$#" 'USER PHPVERSION'
is_format_valid 'user'
is_object_valid 'user' 'USER' "$user"
is_object_unsuspended 'user' 'USER' "$user"

# Perform verification if read-only mode is enabled
check_hestia_demo_mode

# Reading user values
source $USER_DATA/user.conf

versions=$($BIN/v-list-sys-php plain)
support=0
for v in $versions; do
	if [ "$v" == "$version" ]; then
		support=1
	fi
done

if [ "$support" = 0 ]; then
	echo "Version is currently not supported or does not exist..."
	exit 2
fi

# Create .bash_aliases is not exsists
if [ ! -f "$FILE" ]; then
	if [ -f /etc/redhat-release ];then
		mkdir -p $HOMEDIR/$user/.bashrc.d
		chown -R $user:$user $HOMEDIR/$user/.bashrc.d
	fi
	touch $FILE
	chown $user:$user $FILE
fi

if grep -q "alias php='env php$version'" "$FILE"; then
	echo "PHP CLI Already defined"
	exit
fi

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

sed -i "/alias php='env/d" $FILE
echo "alias php='env php$version'" >> $FILE
update_user_value "$user" '$PHPCLI' "$version"

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

$BIN/v-log-action "system" "Info" "Users" "Default PHP CLI version changed (User: $user, Version: $version)."

exit
