#!/bin/bash

. /usr/local/Reductor/etc/const
#shellcheck disable=SC1090
. $CONFIG

set -eu

#shellcheck disable=SC2154
enabled() {
	! [ "${filter['dns']:-0}" = '0' ] && ip_set_well "${filter['dns_ip']:-}"
}

ipv6() {
	enabled && [ "${filter['ipv6']:-0}" = '1' ]
}

ip_set_well() {
	#shellcheck disable=SC2154
	echo "${1:-}" | egrep -q "^$ip_regex$" && [ "${1:-}" != "127.0.0.1" ]
}

ip_mask_set_well() {
	#shellcheck disable=SC2154
	echo "${1:-}" | egrep -q "^$ip_or_ipmask_regex$" && [ "${1:-}" != "127.0.0.1" ]
}

proxy_may_be_used() {
	enabled && ip_set_well "${filter['dns_proxy_ip']}"
}

proxy_https() {
	enabled && proxy_may_be_used && [ "${filter['dns_proxy_url_https']:-}" = '1' ]
}

proxy_hsts() {
	enabled && proxy_may_be_used && [ "${filter['dns_proxy_hsts']:-}" = '1' ]
}

dns_separate_exact_and_mask() {
	[ "${filter['dns_separate_exact_and_mask']:-}" = '1' ]
}

dns_log_enabled() {
	[ "${filter['dns_log_level']}" = '1' ] || [ "${filter['dns_log_level']}" = '2' ]
}

default_blackhole_ip() {
	[ "${filter['dns_ip']:-}" = "$CARBONSOFT_BLACKHOLE" ]
}

sni() {
	[ "${filter['sni']:-}" = "1" ]
}

nginx_ip() {
	local ip="${filter['dns_ip']:-$CARBONSOFT_BLACKHOLE}"
	[ "$ip" != '127.0.0.1' ] || ip=$CARBONSOFT_BLACKHOLE
	echo $ip
}

ext_ip() {
	local ip="$(ip r g 8.8.8.8 | head -1 | awk '{print $7}')"
	echo "$ip" | egrep "^$ip_regex$"
}

ext_dev() {
	local dev="$(ip r g 8.8.8.8 | grep -o 'dev .[^ ]*' | cut -d ' ' -f2)"
	echo "$dev" | egrep "^[a-z0-9]*"
}

revisor() {
	ip_mask_set_well "${filter['revisor_ip']}"
}

if [ "$#" = '0' ] || [ "$1" = '--enabled' ]; then
	enabled
elif [ "$1" = '--ipv6' ]; then
	ipv6
elif [ "$1" = '--revisor' ]; then
	revisor
elif [ "$1" = '--proxy-may-be-used' ]; then
	proxy_may_be_used
elif [ "$1" = '--nginx-ip' ]; then
	nginx_ip
elif [ "$1" = '--proxy-https' ]; then
	proxy_https
elif [ "$1" = '--proxy-hsts' ]; then
	proxy_hsts
elif [ "$1" = '--separate-exact-and-mask' ]; then
	dns_separate_exact_and_mask
elif [ "$1" = '--log-enabled' ]; then
	dns_log_enabled
elif [ "$1" = '--default-blackhole-ip' ]; then
	default_blackhole_ip
elif [ "$1" = '--sni' ]; then
	sni
elif [ "$1" = '--ext-ip' ]; then
	ext_ip
elif [ "$1" = '--ext-dev' ]; then
	ext_dev
else
	log "WARNING: unknown options $*"
	exit 1
fi
