#!/bin/sh

# PROVIDE: ndp-proxy-go
# REQUIRE: NETWORKING
# KEYWORD: shutdown

# To enable ndp-proxy-go:
#
# - Configure interfaces in /etc/rc.conf:
#   # sysrc ndp_proxy_go_enable="YES"
#   # sysrc ndp_proxy_go_upstream="igc1"
#   # sysrc ndp_proxy_go_downstream="igc0"
#
# - Optional flags:
#   # sysrc ndp_proxy_go_flags="--debug"
#
# Settings:
# ndp_proxy_go_enable (bool):       Enable service
# ndp_proxy_go_upstream (string):   Upstream interface
# ndp_proxy_go_downstream (string): Downstream interface(s), space-separated
# ndp_proxy_go_flags (string):      Additional flags (e.g., --debug, --no-ra)
# ndp_proxy_go_cache_file (string): Path to persistent cache file
# ndp_proxy_go_check_carp (bool):   Check if CARP status is MASTER before starting

. /etc/rc.subr

name="ndp_proxy_go"
rcvar="ndp_proxy_go_enable"
desc="IPv6 Neighbor Discovery Protocol (NDP) Proxy"

load_rc_config $name

# Defaults
: ${ndp_proxy_go_enable:=NO}
: ${ndp_proxy_go_upstream:=""}
: ${ndp_proxy_go_downstream:=""}
: ${ndp_proxy_go_flags:=""}
: ${ndp_proxy_go_cache_file:=""}
: ${ndp_proxy_go_check_carp:=""}

command="/usr/local/sbin/ndp-proxy-go"
pidfile="/var/run/${name}.pid"

start_precmd="ndp_proxy_go_precmd"
start_cmd="ndp_proxy_go_start"
stop_precmd="ndp_proxy_go_prestop"

ndp_proxy_go_precmd()
{
    if [ -n "${ndp_proxy_go_check_carp}" ]; then
        if ! ifconfig | grep -q 'carp: MASTER'; then
            return 1
        fi
    fi

    if [ -z "${ndp_proxy_go_upstream}" ]; then
        warn "ndp_proxy_go_upstream not set in rc.conf"
        return 1
    fi
    if [ -z "${ndp_proxy_go_downstream}" ]; then
        warn "ndp_proxy_go_downstream not set in rc.conf"
        return 1
    fi

    # Verify interfaces exist
    if ! ifconfig ${ndp_proxy_go_upstream} > /dev/null 2>&1; then
        warn "upstream interface ${ndp_proxy_go_upstream} does not exist"
        return 1
    fi
    for iface in ${ndp_proxy_go_downstream}; do
        if ! ifconfig ${iface} > /dev/null 2>&1; then
            warn "downstream interface ${iface} does not exist"
            return 1
        fi
    done

    # Create cache directory if cache_file is specified
    if [ -n "${ndp_proxy_go_cache_file}" ]; then
        install -d -m 755 "$(dirname "${ndp_proxy_go_cache_file}")"
    fi
}

ndp_proxy_go_start()
{
    echo "Starting ${name}."
    /usr/sbin/daemon -S -f -s notice -l daemon -T ndpproxy -m 3 -p ${pidfile} \
        ${command} ${ndp_proxy_go_flags} \
        ${ndp_proxy_go_cache_file:+--cache-file "${ndp_proxy_go_cache_file}"} \
        ${ndp_proxy_go_upstream} ${ndp_proxy_go_downstream}
}

ndp_proxy_go_prestop()
{
    # Save cache before stopping if --cache-file is configured
    [ -n "$ndp_proxy_go_cache_file" ] || return 0
    [ -f "$pidfile" ] || return 0
    kill -USR1 "$(cat "$pidfile")" 2>/dev/null
}

run_rc_command "$@"
