#!/usr/local/bin/cbsd
#v10.1.0
MYARG=""
MYOPTARG="nat"
MYDESC="Enable NAT service for RFC1918 Networks"
ADDHELP="nat= name of framework. default in inventory config\n"

. ${subrdir}/nc.subr

. ${cbsdinit}

. ${system}
. ${initenv}

[ -n "${nat}" ] && nat_enable="${nat}"

check_nat_ip()
{
	natoff nat=all
	/sbin/ping -c1 -S ${natip} ${natip} > /dev/null 2>&1 || err 1 "${N1_COLOR}Cant assign nat address: ${N2_COLOR}${natip}${N1_COLOR}. Probably wrong ip. Nat cfg skipped${N0_COLOR}"
}

[ "${nat_enable}" = "0" ] && exit 0
# forwarding for NAT mode
${ECHO} "${N1_COLOR}CBSD: Enable IP forwarding for NAT service${N0_COLOR}"
${SYSCTL_CMD} net.inet6.ip6.forwarding=1 >/dev/null
${SYSCTL_CMD} net.inet.ip.forwarding=1 >/dev/null

iptype ${natip} >/dev/null 2>&1
_ret=$?

# if natip is not valid IPv4, assume it is NIC variable.
# so try to find out first IPv4 for aliasing
case ${_ret} in
	1)
		# natip is valid IPv4
		_extiface="${CBSD_UPLINK_IFACE4}"
		;;
	2)
		# natip is valid IPv6
		_extiface="${CBSD_UPLINK_IFACE6}"
		;;
	*)
		_extiface="${natip}"
		natip=$( getip-by-nics nic=${_extiface} 2>/dev/null )
		if [ $? -ne 0 ]; then
			${ECHO} "${N1_COLOR}Unable to determine first IP for nic: ${N2_COLOR}${_extiface}${N0_COLOR}"
			return 1
		fi
		ok="${nat_enable}" # used by make_nat
		make_nat
		;;
esac

case "${nat_enable}" in
	"pf")
		[ ! -f "${etcdir}/pfnat.conf" ] && err 1 "${N1_COLOR}No pfnat.conf. run ${N2_COLOR}cbsd natcfg${N1_COLOR} first${N0_COLOR}"
		/sbin/kldstat -qm pf || /sbin/kldload pf
		check_nat_ip
		${PFCTL_CMD} -f ${etcdir}/pfnat.conf
		${PFCTL_CMD} -e
	;;
	"ipfw")
		[ ! -f "${etcdir}/ipfw.conf" ] && err 1 "${N1_COLOR}No ipfw.conf. run ${N2_COLOR}cbsd natcfg${N1_COLOR} first${N0_COLOR}"
		/sbin/kldstat -qm alias || /sbin/kldload libalias
		/sbin/kldstat -qm ipfw_nat || /sbin/kldload ipfw_nat
		check_nat_ip
		/bin/sh ${etcdir}/ipfw.conf
	;;
	"ipfilter")
		[ ! -f "${etcdir}/ipfilter.conf" ] && err 1 "No ipfilter.conf. run cbsd natcfg first"
		/sbin/kldstat -qm ipfilter || /sbin/kldload ipfilter
		check_nat_ip
		/sbin/ipnat -CF -f ${etcdir}/ipfilter.conf
	;;
esac
