#!/usr/bin/env bash

# Short-Description: Protect your privacy online and access media content with no regional restrictions. Strong encryption and no-log policy with 3000+ servers in 60+ countries.
### END INIT INFO

PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin

BASE=nordvpn

DAEMON=/usr/sbin/${BASE}d
PID=/run/$BASE.pid
SOCK=/run/$BASE/${BASE}d.sock
SOCKDIR=/run/$BASE

create_socket_dir() {
  mkdir -p "$SOCKDIR"
  chown root:$BASE "$SOCKDIR" 2>/dev/null || true
  chmod 0770 "$SOCKDIR" 2>/dev/null || true
}

# Wait up to ~5s for the daemon to create the socket
wait_for_socket() {
  i=0
  while [ $i -lt 50 ]; do
    [ -S "$SOCK" ] && return 0
    sleep 0.1
    i=$((i+1))
  done
  return 1
}

# Wait up to ~2s for the PID in $PID to exit
wait_for_exit() {
  [ -s "$PID" ] || return 0
  _pid="$(cat "$PID" 2>/dev/null)"
  i=0
  while [ $i -lt 20 ]; do
    [ -n "$_pid" ] && kill -0 "$_pid" 2>/dev/null || return 0
    sleep 0.1
    i=$((i+1))
  done
  return 1
}

#
# Function that starts the daemon
#
nordvpnd_start()
{
  create_socket_dir
  if [ -s "$PID" ]; then
    echo "$BASE is already running: $(cat "$PID")"
    exit 1
  fi

  rm -f -- "$SOCK"

  if [ -x "$DAEMON" ]; then
    echo "Starting $BASE"

    # Scope NordVPN private libs to the daemon only
    if [ -d /usr/lib64/nordvpn ]; then
      _nvlib=/usr/lib64/nordvpn
    elif [ -d /usr/lib/nordvpn ]; then
      _nvlib=/usr/lib/nordvpn
    else
      _nvlib=
    fi
    [ -n "$_nvlib" ] && export LD_LIBRARY_PATH="$_nvlib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"

    "$DAEMON" > /dev/null &
    pidof "${BASE}d" > "$PID"

    if wait_for_socket; then
      chown root:$BASE "$SOCK" 2>/dev/null || true
      chmod 0770 "$SOCK" 2>/dev/null || true
      echo "$BASE has been started."
    else
      echo "$BASE failed to start. Please restart the daemon."
    fi
  fi
}

#
# Function that stops the daemon
#
nordvpnd_stop()
{
  if [ -s "$PID" ]; then
    echo "Stopping $BASE"
    kill "$(cat "$PID")"
    wait_for_exit
    rm -f -- "$PID" "$SOCK"
    echo "$BASE has been stopped."
  else
    echo "$BASE is not running."
  fi
}

#
# Function that restarts the daemon
#
nordvpnd_restart()
{
  nordvpnd_stop
  nordvpnd_start
}

#
# Function that shows the current status of the daemon
#
nordvpnd_status()
{
  if [ -s "$PID" ]; then
    echo "$BASE is running: $(cat "$PID")"
  else
    echo "$BASE is not running."
  fi
}

case "$1" in
  start)
    nordvpnd_start
    ;;
  stop)
    nordvpnd_stop
    ;;
  restart)
    nordvpnd_restart
    ;;
  status)
    nordvpnd_status
    ;;
  *)
    echo $"Usage: $0 {start|stop|restart|status}"
    exit 1
    ;;
esac
