#!/bin/bash

# Check if nordvpn is installed
if [ -z "$(which nordvpn)" ]; then
    pkexec nordvpn-install
    if [ -z "$(which nordvpn)" ]; then
        echo "Nordvpn not installed - exiting"
        exit 1
    fi
fi

PYTHON=$(which python3)
if [ -z "$PYTHON" ]; then
  echo "Cannot find python3 executable - exiting"
  exit 2
fi

NVPNDIR="$HOME/.config/nordvpn"
if [ ! -d $NVPNDIR ]; then
    mkdir -p "$NVPNDIR"
fi

DEBUG=false; case "$@" in -d|--debug) DEBUG=true; esac

if ! pgrep -u $USER -f python3.*nordvpn-indicator &>/dev/null; then
    # Use file as tty output
    # Launch with all passed arguments (future reserved)
    if $DEBUG; then
        # Use importlib to import a module with a hyphen in its name
        $PYTHON -Wd -c "import importlib; ni = importlib.import_module('nordvpn-indicator'); ni.main() $@"
    else
        LOG="$NVPNDIR/indicator.log"
        nohup $PYTHON -OO -c "import importlib; ni = importlib.import_module('nordvpn-indicator'); ni.main() $@" &> $LOG  &
        echo "Output written to $LOG"
        echo "You can now close the terminal."
    fi
fi
