#!/bin/bash
# info: add 2fa to existing user
# options: USER
#
# example: v-add-user-2fa admin
#
# This function creates a new 2fa token 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' 'system'
is_object_valid 'user' 'USER' "$user"

# Perform verification if read-only mode is enabled
check_hestia_demo_mode

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

# Reading user values
source $USER_DATA/user.conf

# Check if 2FA is already enabled
if [ -n "$TWOFA" ]; then
	echo "Error: 2FA already enabled"
	exit "$E_EXISTS"
fi

# Get secret and qr code from 2fa library
data=$($HESTIA_PHP $HESTIA/web/inc/2fa/secret.php)

# Split to secret and qrcode using delimiter
IFS='-' read -r -a array <<< "$data"
secret=${array[0]}
qrcode=${array[1]}

# Save the secret in user config (needs encryption?)
update_user_value "$user" '$TWOFA' "$secret"
update_user_value "$user" '$QRCODE' "$qrcode"

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

exit