#!/bin/bash
# info: open config
# options: CONFIG
#
# example: v-open-fs-config /etc/mysql/my.cnf
#
# This function opens/reads config files on the file system

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

# shellcheck source=/etc/hestiacp/hestia.conf
source /etc/hestiacp/hestia.conf
src_file=$1

# Checking arguments
if [ -z "$src_file" ]; then
	echo "Usage: CONFIG"
	exit 1
fi

# Checking root permissions
if [ "$(id -u)" != '0' ]; then
	echo "Error: Script can be run executed only by root"
	exit 10
fi

# Checking file on fs
if [ ! -e "$src_file" ]; then
	echo "Error: $src_file file doesn't exist"
	exit 3
fi

# Checking path
if [ -n "$src_file" ]; then
	rpath=$(readlink -f "$src_file")
	services="nginx|apache|httpd|php|ftp|bind|named|exim|dovecot|spamassassin"
	services="$services|clam|mysql|postgresql|pgsql|cron|ssh|fail2ban|iptables"
	services="$services|my.cnf"
	spath=$(echo "$rpath" | egrep "$services")
	if [ -z "$spath" ]; then
		echo "Error: invalid source path $src_file"
		exit 2
	fi
	spath=$(echo "$rpath" | egrep "/etc|/var/lib")
	if [ -z "$spath" ]; then
		echo "Error: invalid source path $src_file"
		exit 2
	fi
fi

# Reading conf
cat "$src_file" 2> /dev/null
if [ $? -ne 0 ]; then
	echo "Error: file $src_file was not opened"
	exit 3
fi

$BIN/v-log-action "system" "Info" "System" "Configuration file opened (File: $src_file)."

# Exiting
exit