#!/bin/bash
# info: list letsencrypt key
# options: USER [FORMAT]
#
# example: v-list-letsencrypt-user admin
#
# This function for obtaining the letsencrypt key thumbprint

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

# Argument definition
user=$1
format=${2-shell}

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

# JSON list function
json_list() {
	echo '{'
	echo '    "'$user'": {
        "EMAIL": "'$EMAIL'",
        "EXPONENT": "'$EXPONENT'",
        "MODULUS": "'$MODULUS'",
        "THUMB": "'$THUMB'",
        "KID": "'$KID'"
    }'
	echo '}'
}

# SHELL list function
shell_list() {
	echo "USER:           $user"
	echo "EMAIL:          $EMAIL"
	echo "THUMB:          $THUMB"
	echo "EXPONENT:       $EXPONENT"
	echo "MODULUS:        $MODULUS"
	echo "KID:            $KID"
}

# PLAIN list function
plain_list() {
	echo -e "$user\t$EMAIL\t$EXPONENT\t$MODULUS\t$THUMB\t$KID"
}

# CSV list function
csv_list() {
	echo "USER,EMAIL,EXPONENT,MODULUS,THUMB,KID"
	echo "$user,$EMAIL,$EXPONENT,$MODULUS,$THUMB,$KID"
}

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

check_args '1' "$#" 'USER [FORMAT]'
is_format_valid 'user'
is_object_valid 'user' 'USER' "$user"
if [ ! -e "$USER_DATA/ssl/le.conf" ]; then
	check_result "$E_NOTEXIST" "LetsEncrypt user account doesn't exist"
fi

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

# load config file
source_conf "$USER_DATA/ssl/le.conf"

# Listing data
case $format in
	json) json_list ;;
	plain) plain_list ;;
	csv) csv_list ;;
	shell) shell_list ;;
esac

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

exit
