#!/bin/bash

# Includes
# shellcheck source=/etc/hestiacp/hestia.conf
source /etc/hestiacp/hestia.conf
# load config file
source_conf "$HESTIA/conf/hestia.conf"

# Variables and arguments
HESTIA="/usr/local/hestia"
script=$1
log=$2
mode=${3-$2}

if [ "$DEBUG_MODE" = "no" ] || [ -z "$DEBUG_MODE" ]; then
	echo "ERROR: Developer mode is disabled."
	echo "Enable with v-change-sys-config-value DEBUG_MODE yes"
	exit 1
fi

if [ -z "$script" ]; then
	echo "ERROR: No script specified."
	echo "Usage:    v-generate-debug-report v-script-name LOG_OUTPUT"
	echo ""
	echo "Example:  v-generate-debug-report v-add-user yes"
	echo "          Log output to file located in ~/hst-debug/"
	echo ""
	echo "Example:  v-generate-debug-report v-list-web-domains"
	echo "          Show output in console."
	echo ""
	exit 1
fi

# Install shellcheck
package_check=$(dpkg -l | grep shellcheck)
if [ -z "$package_check" ]; then
	echo "[ * ] Updating APT package cache..."
	apt-get -qq update > /dev/null 2>&1
	echo "[ * ] Installing shellcheck code linter..."
	apt-get -qq install -y shellcheck > /dev/null 2>&1
fi

# Set debug path and ensure it exists
DEBUG_PATH="$HOME/hst-debug/"
if [ ! -d "$DEBUG_PATH" ]; then
	mkdir "$DEBUG_PATH"
fi

# Generate timestamp
time_n_date=$(date +'%F %T')
time_n_date=$(echo "$time_n_date" | sed "s|:||g" | sed "s| |_|g")

# If logging specified, export shellcheck output to log
if [ "$log" = "yes" ]; then
	if [ "$mode" = "all" ]; then
		shellcheck -x "$BIN/$script" > "$DEBUG_PATH/${script}_$time_n_date.log"
	fi
	if [ "$mode" = "warn" ]; then
		shellcheck -x -e "SC2086,SC1090,SC2154,SC2153" "$BIN/$script" > "$DEBUG_PATH/${script}_$time_n_date.log"
	else
		shellcheck -x -e "SC2086,SC2016,SC2153,SC2154,SC1090,SC2034,SC2119" "$BIN/$script" > "$DEBUG_PATH/${script}_$time_n_date.log"
	fi
else
	# Prompt user to scroll output from shellcheck
	clear
	if [ "$mode" = "all" ]; then
		shellcheck -x "$BIN/$script"
	fi
	if [ "$mode" = "warn" ]; then
		shellcheck -x -e "SC2086,SC1090,SC2154,SC2153" "$BIN/$script"
	else
		shellcheck -x -e "SC2086,SC2016,SC2153,SC2154,SC1090,SC2034,SC2119" "$BIN/$script"
	fi
fi