#!/bin/bash
# info: check api key
# options: KEY [IP]
#
# example: v-check-api-key random_key 127.0.0.1
#
# This function checks a key file in $HESTIA/data/keys/

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

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

new_timestamp

abort_missmatch() {
	echo "Error: key missmatch"
	echo "$date $time api $ip failed to login" >> $HESTIA/log/auth.log
	exit "$E_PASSWORD"
}

ip=${2-127.0.0.1}
time_n_date=$(date +'%T %F')
time=$(echo "$time_n_date" | cut -f 1 -d \ )
date=$(echo "$time_n_date" | cut -f 2 -d \ )

# Perform verification if read-only mode is enabled
check_hestia_demo_mode

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

key="$(basename "$1")"

# Exit if Key is unset or to short
[[ -z $key || ${#key} -lt 16 ]] && abort_missmatch

# Key file must exist
maybe_key_path="$(readlink -e "${HESTIA}/data/keys/${key}")"
[[ -z $maybe_key_path ]] && abort_missmatch

# Key file cannot be the key store
[[ $maybe_key_path == "${HESTIA}/data/keys" ]] && abort_missmatch

# Key file must be in the key store
[[ $maybe_key_path == "${HESTIA}/data/keys/"* ]] || abort_missmatch

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

echo "$date $time api $ip successfully launched" >> $HESTIA/log/auth.log

exit
