#!/bin/sh

### BEGIN INIT INFO
# Provides:     vipnetclient
# Required-Start:   $local_fs $network $syslog
# Required-Stop:    $local_fs $network $syslog
# Default-Start:    2 3 4 5
# Default-Stop:     0 1 6
# Short-Description:    ViPNet Client for Linux
### END INIT INFO

PATH="/sbin:/bin:/usr/sbin:/usr/bin"
NAME="vipnetclient"
DESC="ViPNet Client for Linux"
CONF="/etc/vipnet.conf"

test -x /usr/bin/${NAME} || exit 0

[ -f /lib/lsb/init-functions ] && . /lib/lsb/init-functions

# These variables for OpenWrt init compatibility
START=90
STOP=10

# These functions for OpenWrt init compatibility
start()
{
    local root_vipnet_dir=$(awk -F= '/^config_dir=/ {print $2}' $CONF 2>/dev/null)
    root_vipnet_dir=${root_vipnet_dir:-~root/.vipnet}

    [ -d "${root_vipnet_dir}" ] || { echo "ViPNet keys for root are absent" >&2; exit 0; }

    which killall >/dev/null && killall -9 /usr/bin/${NAME} # if there are any instances, terminate them at first

    /usr/bin/${NAME} info >/dev/null 2>&1
    /usr/bin/${NAME} start
}

stop()
{
    /usr/bin/${NAME} stop
}

status()
{
    /usr/bin/${NAME} info
}

case "${1}" in
    start)          start ;;
    stop)           stop ;;
    restart)        stop; start ;;
    status|info)    status ;;
    "")             ;;
    *) echo "Usage: ${0} {start|stop|restart|status|info}" >&2 ;;
esac
