#!/bin/sh

# PROVIDE: hev6
# REQUIRE: NETWORKING FILESYSTEMS
# KEYWORD: shutdown

# This script provided by CrtxReaver
# Set the following:
# - hev6_remotev4ip
# - hev6_localv6ip
# - hev6_remotev6ip

. /etc/rc.subr

name="hev6"
rcvar=`set_rcvar`
start_cmd="hev6_start"
stop_cmd="hev6_stop"
start_precmd="hev6_precmd"


hev6_precmd()
{
    # Safe Defaults
    tunnelpint=$(route get default | grep interface\: | cut -d' ' -f4)
    tunnelvint="gif6"
    tunnelpreflen=64

    remotev4ip=$hev6_remotev4ip
    localv6ip=$hev6_localv6ip
    remotev6ip=$hev6_remotev6ip

    localv4ip=$(ifconfig $tunnelpint | grep 'inet ' | head -1 | cut -d' ' -f2)
}

hev6_start()
{
    if checkyesno ${rcvar}; then
        ifconfig $tunnelvint create && \
        ifconfig $tunnelvint tunnel $localv4ip $remotev4ip && \
        ifconfig $tunnelvint inet6 $localv6ip/$tunnelpreflen && \
        route -qn add -inet6 default $remotev6ip && \
        ifconfig $tunnelvint up
    fi
}

hev6_stop()
{
    tunnelvint="gif6"
    if checkyesno ${rcvar}; then
        route -qn delete -inet6 default && \
        ifconfig $tunnelvint down && \
        ifconfig $tunnelvint destroy
    fi
}

load_rc_config $name
run_rc_command "$1"
