#!/bin/sh
#
# $FreeBSD$
#
# PROVIDE: tayga
# REQUIRE: SERVERS
# KEYWORD: shutdown
#

. ${RC_ROUTER_HARNESS}/etc/rc.subr

name='tayga'

start_cmd='tayga_start'
stop_cmd='tayga_stop'
rcvar='tayga_enable'

load_rc_config 'tayga'
pidfile="/var/run/${name}.pid"
command="/usr/local/sbin/${name}"

# Confirm necessary variables are set
check_vars()
{
    [ -z "$tayga_ipv4_addr" ] && err 3 "Must set tayga_ipv4_addr to the address that the tayga server lives on"
    [ -z "$tayga_ipv4_endpoint" ] && err 3 "Must set tayga_ipv4_endpoint to the address that the tunnel lives on"
    [ -z "$tayga_ipv4_net" ] && err 3 "Must set tayga_ipv4_net to the network that the tunnel lives on"
    [ -z "$tayga_ipv6_endpoint" ] && err 3 "Must set tayga_ipv6_endpoint to the address that the tunnel lives on"
    [ -z "$tayga_ipv6_net" ] && err 3 "Must set tayga_ipv6_net to the network that the tunnel provides"
}

[ -z "$tayga_config" ] && tayga_config="/usr/local/etc/tayga.conf"

command_args="-p ${pidfile} -c ${tayga_config}"

[ -z "$tayga_enable" ] && tayga_enable='YES'

tayga_start()
{
    check_vars
    "$command" $command_args
    while ! ifconfig 'nat64'; do sleep 1; done
    ifconfig 'nat64' inet "${tayga_ipv4_endpoint}/32" "${tayga_ipv4_addr}"
    if [ ! -z "${tayga_group}" ] ; then ifconfig 'nat64' group ${tayga_group} ; fi
    ifconfig 'nat64' inet6 "${tayga_ipv6_endpoint}/128"
    #echo Add route 4
    route -4 add "${tayga_ipv4_net}" -interface 'nat64'
    #echo Add route 6 for endpoint from net
    #route -6 add "${tayga_ipv6_endpoint}" -iface 'nat64' #-fib 0-7
    route -6 add "${tayga_ipv6_net}" "${tayga_ipv6_endpoint}" #-fib 0-7
    #echo Add route 6 for endpoint subnet
    route -6 add "${tayga_ipv6_endpoint}/64" "${tayga_ipv6_endpoint}" #-fib 0-7

    for prefix in ${tayga_v4_prefixes}
    do
        route add ${prefix} ${tayga_ipv4_addr} -fib 0-${max_fib}
    done
}

tayga_stop()
{
    if [ -n "$rc_pid" ]; then
        check_vars

        for prefix in tayga_v4_prefixes
        do
            route del ${prefix} ${tayga_ipv4_addr} -fib 0-${max_fib}
        done

        echo 'stopping tayga'
        kill -2 "${rc_pid}"
        route -6 del "${tayga_ipv6_net}" -interface 'nat64'
        route -4 del "${tayga_ipv4_net}" -interface 'nat64'
        ifconfig 'nat64' destroy
    else
        echo "${name} is not running."
    fi
}

run_rc_command "$1"
