#!/bin/sh
### BEGIN INIT INFO
# Provides:          tailscaled
# Required-Start:    $network $local_fs
# Required-Stop:     $network $local_fs
# Default-Start:     3 4 5
# Default-Stop:      0 1 2 6
# Short-Description: Tailscale node agent
# Description:       Start the Tailscale daemon.
### END INIT INFO

PATH=/sbin:/usr/sbin:/bin:/usr/bin
DAEMON=/usr/sbin/tailscaled
PIDFILE=/var/run/tailscaled.pid
NAME=tailscaled
DESC="Tailscale node agent"

test -x $DAEMON || exit 0

set -e

. /etc/init.d/functions

if [ -f /etc/default/tailscaled ] ; then
    . /etc/default/tailscaled
fi

delay_stop() {
    count=0
    while [ $count -lt 9 ] ; do
        if pidof $DAEMON >/dev/null; then
            sleep 1
        else
            return 0
        fi
        count=$(expr $count + 1)
    done
    echo "Failed to stop $DESC."
    return 1
}

case "$1" in
    start)
        echo -n "starting $DESC: $NAME... "
        start-stop-daemon --start --background --make-pidfile --pidfile $PIDFILE \
                --exec $DAEMON -- $ARGS
        echo "done."
        ;;
    stop)
        echo -n "stopping $DESC: $NAME... "
        start-stop-daemon --stop --pidfile $PIDFILE
        echo "done."
        ;;
    restart)
        $0 stop
        delay_stop && $0 start
        ;;
    status)
        status $DAEMON
        exit $?
        ;;
    *)
        echo "Usage: $0 {start|stop|restart|status}"
        exit 1
        ;;
esac

exit 0
