#!/bin/bash
# info: add wp-cli for a user
# options: USER
#
# example: v-add-user-wp-cli user
#
# This function adds support for wp-cli to the user account

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

# Argument definition
user=$1

if [ -z "$HESTIA" ]; then
	HESTIA="/usr/local/hestia"
fi

# 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'
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                             #
#----------------------------------------------------------#

WPCLI_DIR="/home/$user/.wp-cli"
WPCLI_BIN="$WPCLI_DIR/wp"

if [ -f "$WPCLI_BIN" ]; then
	check_result "$E_EXISTS" "For user name '$user' WP-CLI already available!"
	exit
fi

[ -z "$(readlink -m "$WPCLI_DIR" | egrep "^$HOMEDIR/$user/")" ] && check_result "$E_FORBIDEN" "Path outside of user homedir (WP Cli dir)"
[ -z "$(readlink -m "$WPCLI_BIN" | egrep "^$HOMEDIR/$user/")" ] && check_result "$E_FORBIDEN" "Path outside of user homedir (WP Cli bin)"

mkdir -p "$WPCLI_DIR"
chown $user:$user "$WPCLI_DIR"

user_exec wget --tries=3 --timeout=15 --read-timeout=15 --waitretry=3 --no-dns-cache --quiet -O "$WPCLI_BIN" https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar
user_exec chmod +x "$WPCLI_BIN"
user_exec echo -e "#add wp-cli alias for user\nalias wp='php $WPCLI_BIN'" >> ~/.bashrc

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

# Logging
$BIN/v-log-action "$user" "Info" "Plugins" "WP-CLI support enabled."
log_event "$OK" "$ARGUMENTS"

exit