#!/bin/bash
# info: Purge nginx cache
# options: USER DOMAIN
#
# example: v-purge-nginx-cache user domain.tld
#
# This function purges nginx cache.

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

# Argument definition
user=$1
domain=$2
restart=$3

# 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
# shellcheck source=/usr/local/hestia/conf/hestia.conf
source $HESTIA/conf/hestia.conf
# load config file
source_conf "$HESTIA/conf/hestia.conf"

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

check_args '2' "$#" 'USER DOMAIN [RESTART]'
is_format_valid 'user' 'domain' 'restart'
is_object_valid 'user' 'USER' "$user"
is_object_unsuspended 'user' 'USER' "$user"
is_object_valid 'web' 'DOMAIN' "$domain"
is_object_unsuspended 'web' 'DOMAIN' "$domain"
is_object_valid 'web' 'DOMAIN' "$domain" "$FASTCGI_CACHE"

# Perform verification if read-only mode is enabled
check_hestia_demo_mode

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

conf=$(grep "DOMAIN='$domain'" "$USER_DATA/web.conf")
parse_object_kv_list "$conf"

# Purge nginx FastCGI cache
if [ -d "/var/cache/nginx/micro/$domain" ]; then
	rm -rf /var/cache/nginx/micro/$domain/*
fi

# Purge nginx proxy cache
if [ -d "/var/cache/nginx/$domain" ]; then
	rm -rf /var/cache/nginx/$domain/*
fi

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

# Restart services if requested
if [ "$restart" != "no" ]; then
	$BIN/v-restart-web "$restart"
	check_result $? "Web restart failed" > /dev/null

	$BIN/v-restart-proxy "$restart"
	check_result $? "Proxy restart failed" > /dev/null

fi

# Logging
$BIN/v-log-action "$user" "Info" "Web" "Cache purged (Domain: $domain)."
log_event "$OK" "$ARGUMENTS"

exit