#!/usr/local/bin/cbsd
MYARG="jname"
MYOPTARG="file nameserver"
MYDESC="Manage jail /etc/resolv.conf file"
ADDHELP="
${H3_COLOR}Description${N0_COLOR}:

The script creates the configuration in /etc/resolv.conf file within jail.
Script works automatically upon 'jstart' command if the container has 'floatresolv=1'.

By default we set the addresses specified as 'jnameserver' in 'initenv-tui'

${H3_COLOR}Options${N0_COLOR}:

 ${N2_COLOR}file=${N0_COLOR}           - use/copy file as /etc/resolv.conf;
 ${N2_COLOR}nameserver=${N0_COLOR}     - overwrite 'jnameserver' IPs, commas as delimer when multiple;

${H3_COLOR}Examples${N0_COLOR}:

 # cbsd makeresolv jname=test1 nameserver=8.8.8.8,8.8.4.4,2001:4860:4860::8888,2001:4860:4860::8844

${H3_COLOR}See also${N0_COLOR}:

 cbsd initenv-tui --help
 Profiles/Skel dir, URL: https://www.bsdstore.ru/en/13.0.x/wf_profiles_ssi.html

"

. ${subrdir}/nc.subr
file=
nameserver=
. ${cbsdinit}

set_resolvconf()
{
	local _i
	local _tpl="CBSD makeresolv function"

	local IFS

	if [ -n "${file}" ]; then
		[ ! -r "${file}" ] && err 1 "${N1_COLOR}${CBSD_APP}: no such file: ${N2_COLOR}${file}${N0_COLOR}"
		${CP_CMD} -a ${file} ${data}/etc/resolv.conf
		return 0
	fi

	IFS=","
	for _i in ${jnameserver}; do
		IFS=" "
		iptype ${_i}
		_ret=$?
		case "${_ret}" in
			0)
				# ???
				;;
			1)
				[ ${jail_has_v4} -eq 1 ] && echo "nameserver ${_i}   # ${_tpl}" >> ${data}/etc/resolv.conf
				;;
			2)
				[ ${jail_has_v6} -eq 1 ] && echo "nameserver ${_i}   # ${_tpl}" >> ${data}/etc/resolv.conf
				;;
		esac
		IFS=","
	done
	IFS=" "
}

unset_resolvconf()
{
	local _tpl="CBSD makeresolv function"

	if [ -n "${nameserver}" -o -z "${file}" ]; then
		# nameserver if preferr to file
		if ${GREP_CMD} "${_tpl}" ${data}/etc/resolv.conf >/dev/null 2>&1; then
			${CP_CMD} -a ${data}/etc/resolv.conf ${data}/etc/resolv.conf.bak
			${GREP_CMD} -v "${_tpl}" ${data}/etc/resolv.conf.bak |${GREP_CMD} "." > ${data}/etc/resolv.conf
		fi
	else
		# just copy file
		${CP_CMD} -a ${data}/etc/resolv.conf ${data}/etc/resolv.conf.bak
	fi
}

. ${subrdir}/rcconf.subr
[ $? -eq 1 ] && err 1 "${N1_COLOR}no such jail: ${N2_COLOR}${jname}${N0_COLOR}"
[ ${floatresolv} -eq 0 ] && exit 0
[ -z "${nameserver}" ] && nameserver="${jnameserver}"
[ -z "${nameserver}" -o "${nameserver}" = "0" ] && exit 0

# v4/v6 flag?
jail_has_v4=0
jail_has_v6=0

if [ "${ip4_addr}" = "0" ]; then
	# assume full stack jail
	jail_has_v4=1
	jail_has_v6=1
else
	OIFS="${IFS}"
	IFS=","
	for _i in ${ip4_addr}; do
		IFS="${OIFS}"
		ipwmask ${_i}
		if [ -z "${IWM}" -o "${_i}" = "0" ]; then
			IFS=","
			continue
		fi

		iptype ${IWM}
		_ret=$?
		case "${_ret}" in
			0)
				case "${IWM}" in
					[Dd][Hh][Cc][Pp])
						jail_has_v4=1
						;;
					[Dd][Hh][Cc][Pp][vV]6)
						jail_has_v6=1
						;;
				esac
				;;
			1)
				jail_has_v4=1
				;;
			2)
				jail_has_v6=1
				;;
			*)
				# ??
				;;
		esac

		IFS=","
	done
fi
OIFS="${IFS}"

unset_resolvconf
set_resolvconf

exit 0
