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

. /etc/rc.subr

name=ddclient_opn
rcvar=ddclient_opn_enable
command=/usr/local/opnsense/scripts/ddclient/ddclient_opn.py
command_interpreter=/usr/local/bin/python3
pidfile="/var/run/${name}.pid"
load_rc_config $name

# Set defaults
: ${ddclient_opn_enable:=NO}

start_postcmd=ddclient_opn_poststart
stop_cmd=ddclient_opn_stop

ddclient_opn_poststart()
{
  # give the daemon some time to initialize its configuration
  for i in 1 2 3 4 5; do
    sleep 1

    if [ -s ${rc_pid} ]; then
      break
    fi
  done
}

ddclient_opn_stop()
{
    if [ -z "$rc_pid" ]; then
        [ -n "$rc_fast" ] && return 0
        _run_rc_notrunning
        return 1
    fi
    echo -n "Stopping ${name}."
    kill -15 ${rc_pid}
    # wait max 2 seconds for gentle exit
    for i in $(seq 1 20);
    do
      if [ -z "`/bin/ps -ex | /usr/bin/awk '{print $1;}' | /usr/bin/grep "^${rc_pid}"`" ]; then
        break
      fi
      sleep 0.1
    done

    for ddclient_pid in `/bin/ps -ex | grep 'ddclient_opn.py' | /usr/bin/awk '{print $1;}' `
    do
      kill -9 $ddclient_pid >/dev/null 2>&1
    done

    echo  "..done"
}

run_rc_command $1
