#! /usr/bin/env bash
#
# Copyright (c) 2021 ExpressVPN. All rights reserved.
#

### BEGIN INIT INFO
# Provides:          expressvpn
# Required-Start:    $remote_fs $network
# Required-Stop:     $remote_fs $network
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start expressvpn at boot time
### END INIT INFO

# Do NOT "set -e"

PATH=/sbin:/usr/sbin:/bin:/usr/bin
DESC="ExpressVPN service"
NAME=expressvpnd
DAEMON=/usr/sbin/$NAME
DAEMON_ARGS=(--client-version "3.49.0beta" --client-build "0")
PIDFILE=/var/run/$NAME.pid
SCRIPTNAME=/etc/init.d/expressvpn

# Exit if the package is not installed
[ -x "$DAEMON" ] || exit 5

# Read configuration variable file if it is present
[ -r /etc/default/$NAME ] && . /etc/default/$NAME

STDOUT=${STDOUT:-"/dev/null"}
STDERR=${STDERR:-"/dev/null"}

# Load the VERBOSE setting and other rcS variables
[ -f /lib/init/vars.sh ] && . /lib/init/vars.sh

# To be replaced by LSB functions.
function log_daemon_msg() {
    echo -n "$@"
}

# To be replaced by LSB functions.
function log_end_msg() {
    retval=$1
    if [ "$retval" -eq 0 ]; then
        echo " [ OK ]"
    else
        echo " [ FAILED ]"
    fi
    return "$retval"
}

# To be replaced by LSB functions.
function log_action_msg() {
    echo "$*." || true
}

# Define LSB log_* functions.
# Depend on lsb-base (>= 3.2-14) to ensure that this file is present
# and status_of_proc is working.
[ -f /lib/lsb/init-functions ] && . /lib/lsb/init-functions


function pidofproc() {
    if [ $# -ne 3 ]; then
        echo "Expected three arguments, e.g. $0 -p pidfile daemon-name"
    fi

    local PID PIDFILE
    PID=$(pgrep -f "$3")
    PIDFILE=$(cat "$2")

    if [ "x$PIDFILE" == "x" ]; then
        return 1
    fi

    if [ "x$PID" != "x" ] && [ "$PIDFILE" == "$PID" ]; then
        return 0
    fi

    return 1
}

function killproc() {
    if [ $# -ne 3 ]; then
        echo "Expected three arguments, e.g. $0 -p pidfile signal"
    fi

    local PID
    PID=$(cat "$2")

    /bin/kill -s "$3" "$PID"
    while true; do
        if pidof "$(basename "$DAEMON")" >/dev/null; then
            return 0
        fi

        sleep 1
        n=$(( "$n" + 1 ))
        if [ "$n" -eq 30 ]; then
            /bin/kill -s SIGKILL "$PID"
            return 0
        fi
    done
}

#
# Function that starts the daemon/service
#
do_start()
{
    # Return
    #   0 if daemon has been started
    #   1 if daemon was already running
    #   2 if daemon could not be started
    if command -v start-stop-daemon > /dev/null 2>&1; then
        nohup start-stop-daemon --start --quiet -m --pidfile "$PIDFILE" --exec "$DAEMON" -- "${DAEMON_ARGS[@]}" >>"$STDOUT" 2>>"$STDERR" &
    else
        su -s /bin/sh -c "nohup $DAEMON -pidfile $PIDFILE ${DAEMON_ARGS[*]} >>$STDOUT 2>>$STDERR &"
    fi

    # Add code here, if necessary, that waits for the process to be ready
    # to handle requests from services started subsequently which depend
    # on this one.  As a last resort, sleep for some time.
    sleep 1

    if /usr/bin/expressvpn status > /dev/null 2>&1; then
        return 0
    else
        return 2
    fi
}

#
# Function that stops the daemon/service
#
do_stop()
{
    # Return
    #   0 if daemon has been stopped
    #   1 if daemon was already stopped
    #   2 if daemon could not be stopped
    #   other if a failure occurred
    if command -v start-stop-daemon > /dev/null 2>&1; then
        start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 --pidfile "$PIDFILE" --name "$NAME"
           
        RETVAL="$?"
        [ "$RETVAL" = 2 ] && return 2
        # Wait for children to finish too if this is a daemon that forks
        # and if the daemon is only ever run from this initscript.
        # If the above conditions are not satisfied then add some other code
        # that waits for the process to drop all resources that could be
        # needed by services started subsequently.  A last resort is to
        # sleep for some time.
        start-stop-daemon --stop --quiet --oknodo --retry=0/30/KILL/5 --exec $DAEMON
        [ "$?" = 2 ] && return 2
        # Many daemons don't delete their pidfiles when they exit.
        rm -f "$PIDFILE"
        return "$RETVAL"
    else
        # Stop the daemon.
        if [ -e "$PIDFILE" ]; then
            local PID
            PID="$(pgrep -f "$PIDFILE")"
            if test ! -z "$PID" && kill -0 "$PID" &>/dev/null; then
                if killproc -p "$PIDFILE" SIGTERM && /bin/rm -rf "$PIDFILE"; then
                    return 0
                else
                    return 2
                fi
            fi
        else
            return 1
        fi
    fi
}

case "$1" in
  start)
    log_daemon_msg "Starting $DESC" "$NAME"
    do_start
    case "$?" in
        0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
        2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
    esac
    ;;
  stop)
    log_daemon_msg "Stopping $DESC" "$NAME"
    do_stop
    case "$?" in
        0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
        2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
    esac
    ;;
  status)
    status_of_proc "$DAEMON" "$NAME" && exit 0 || exit $?
    ;;
  restart)
    log_daemon_msg "Restarting $DESC" "$NAME"
    do_stop
    case "$?" in
      0|1)
        do_start
        case "$?" in
            0) log_end_msg 0 ;;
            1) log_end_msg 1 ;; # Old process is still running
            *) log_end_msg 1 ;; # Failed to start
        esac
        ;;
      *)
        # Failed to stop
        log_end_msg 1
        ;;
    esac
    ;;
*)
    log_action_msg "Usage: $SCRIPTNAME {start|stop|status|restart|force-reload}" || true
    exit 1
    ;;
esac

:
