#!/bin/bash

# import node variables
source /home/pi/monitoring/common/scripts/common_var

# functions
function print_usage() {
cat <<EOF
Usage:

  node_cs [OPTION]...

Options:

    -w, --wlan INTERFACE[ INTERFACE...]
      Specify one or more 2.4GHz wlan interfaces(s).
    
    -w5, --wlan5 INTERFACE[ INTERFACE...]
      Specify one or more 5GHz wlan interfaces(s).
    
    -b, --bt INTERFACE [AMNESIA]
      Specify exactly one bluetooth interface.
      Amnesia mode makes Bluelog forget logged devices older than set
      ammount of time in minutes (device will be logged again, as if
      it was seen for the first time).
    
    --help
      Print help page.

All specified interfaces MUST exist.
Multiple wlan interfaces MUST be enclosed in apostrophes (').
Argument 'remove' will delete existing service.

Examples:

  node_cs -b hci0
  node_cs -b remove
  node_cs -w5 usbwlan5ghz
  node_cs -w usbwlan0 -b hci0 15
  node_cs -w 'usbwlan0 usbwlan1 usbwlan2'

EOF
}

function print_help() {
cat <<EOF

NODE: CREATE MONITORING SYSTEMD SERVICE

This command is used to create systemd service for specified wlan or bluetooth
interface. It will create .service file in systemd directory. This created
service will handle node_dump script calling at startup or for current
session which can be controlled by node_service script. Service must be
enabled/started manually with node_service script after creation.

For more information try using 'node_dump --help'.

There is separate option for 2.4GHz and 5GHz wlan interfaces (-w and -w5).

Note that the node_dump script started by this service will sleep for $DUMP_SLEEP
(defined in node_var) before starting monitoring. This ensures correct
execution of node_dump script after boot.

Systemd directory:        ${DIR_SYSTEMD_SERVICE}

2.4GHz wlan service name: ${SERVICE_NODE_WLAN}
5GHz wlan service name:   ${SERVICE_NODE_WLAN_5GHZ}
Bluetooth service name:   ${SERVICE_NODE_BT}

Location cannot be altered because scripts on this or remote device
might be depending on it!

EOF
print_usage
}

function write_service_wlan() {

  echo "Creating file ${DIR_SYSTEMD_SERVICE}/${SERVICE_NODE_WLAN}..."
  cat << EOF > "${DIR_SYSTEMD_SERVICE}/${SERVICE_NODE_WLAN}"
[Unit]
Description=Monitoring node 2.4GHz wlan service
After=networking.service
Requires=networking.service

[Service]
Type=forking
ExecStart=${DIR_NODE_SCRIPTS}/node_dump -w '${intf_wlan}'

[Install]
WantedBy=multi-user.target
EOF

  # reload systemd daemon to register new service
  echo "Reloading systemd daemon..."
  systemctl daemon-reload
}

function write_service_wlan_5ghz() {

  echo "Creating file ${DIR_SYSTEMD_SERVICE}/${SERVICE_NODE_WLAN_5GHZ}..."
  cat << EOF > "${DIR_SYSTEMD_SERVICE}/${SERVICE_NODE_WLAN_5GHZ}"
[Unit]
Description=Monitoring node 5GHz wlan service
After=networking.service
Requires=networking.service

[Service]
Type=forking
ExecStart=${DIR_NODE_SCRIPTS}/node_dump -w5 '${intf_wlan_5ghz}'

[Install]
WantedBy=multi-user.target
EOF

  # reload systemd daemon to register new service
  echo "Reloading systemd daemon..."
  systemctl daemon-reload
}

function write_service_bt() {

  # no amnesia?
  if [[ "$bt_amnesia" == "" ]];
  then
    
    ExecStart="ExecStart=${DIR_NODE_SCRIPTS}/node_dump -b ${intf_bt}";
    
  else
    
    ExecStart="ExecStart=${DIR_NODE_SCRIPTS}/node_dump -b ${intf_bt} ${bt_amnesia}";
    echo "Bluelog amnesia set to ${bt_amnesia} minutes!"

  fi

  echo "Creating file ${DIR_SYSTEMD_SERVICE}/${SERVICE_NODE_BT}..."
  cat << EOF > "${DIR_SYSTEMD_SERVICE}/${SERVICE_NODE_BT}"
[Unit]
Description=Monitoring node bluetooth service
After=bluetooth.service
Requires=bluetooth.service

[Service]
Type=forking
${ExecStart}

[Install]
WantedBy=multi-user.target
EOF
  
  # reload systemd daemon to register new service
  echo "Reloading systemd daemon..."
  systemctl daemon-reload
}

function create_service() {
  # first argument - name of service
  # return 0 - write service
  # return # - do NOT write service

  # check if service file already exists
  echo "Checking if service ${1} already exists..."
  if [ -f "${DIR_SYSTEMD_SERVICE}/${1}" ];
  then
    echo "Service ${1} already exists!"
    # ask to replace existing service
    read -p "Do you want to replace it? (y/n) " i_replace
    if [ "$i_replace" == "y" ] || [ "$i_replace" == "Y" ]
    then
      # replacing existing service
      echo "File ${DIR_SYSTEMD_SERVICE}/${1} will be replaced!"
      echo "Stopping service ${1}..."
      systemctl stop "${1}"
      echo "Disabling service ${1}..."
      systemctl disable "${1}"
      echo "Removing existing service ${1}..."
      rm "${DIR_SYSTEMD_SERVICE}/${1}"
      return 0
    elif [ "$i_replace" == "n" ] || [ "$i_replace" == "N" ]
    then
      # not replacing existing - exit
      echo "Existing service ${1} unchanged!"
      return 1
    else
      # invalid input - exit
      echo "ERROR: invalid input - expecting y/Y/n/N"
      echo "Existing service ${1} unchanged!"
      return 1
    fi
  else
    echo "Service ${1} does not exist yet!"
    return 0
  fi
}

function remove_service() {
  # first argument - name of the service

  # check if service exists
  echo "Checking if service ${1} exists..."
  if [ -f "${DIR_SYSTEMD_SERVICE}/${1}" ];
  then
    echo "Service ${1} will be removed!"
    echo "Stopping service ${1}..."
    systemctl stop "${1}"
    echo "Disabling service ${1}"
    systemctl disable "${1}"
    echo "Removing service ${1}..."
    rm "${DIR_SYSTEMD_SERVICE}/${1}"
    echo "Reloading systemd daemon..."
    systemctl daemon-reload
  else
    echo "Service ${1} does not exist!"
  fi
  
  return 0  
}

# options parsing

if [[ $# -eq 0 ]];
then
  echo ""
  print_usage
  exit 1
fi  

while [ $# -gt 0 ]
do
  case $1 in
    --help)
      print_help
      exit 0
      ;;
    
    -w|--wlan)
      # check if argument -w empty
      if [[ -z "$2" ]] || [[ "$2" == -* ]];
      then
        echo "ERROR: invalid argument '${2}' for option '${1}'"
        print_usage
	exit 1
        break
      fi

      # check if option is remove
      if [[ "$2" == "remove" ]];
      then
        remove_service $SERVICE_NODE_WLAN
      else
        intf_wlan="$2"
        if create_service ${SERVICE_NODE_WLAN} ;
        then
          write_service_wlan
        fi
      fi

      shift
      ;;
    
    -w5|--wlan5)
      # check if argument -w5 empty
      if [[ -z "$2" ]] || [[ "$2" == -* ]];
      then
        echo "ERROR: invalid argument '${2}' for option '${1}'"
        print_usage
	exit 1
        break
      fi

      # check if option is remove
      if [[ "$2" == "remove" ]];
      then
        remove_service $SERVICE_NODE_WLAN_5GHZ
      else
        intf_wlan_5ghz="$2"
        if create_service ${SERVICE_NODE_WLAN_5GHZ} ;
        then
          write_service_wlan_5ghz
        fi
      fi

      shift
      ;;
    
    -b|--bt)
      # arguments
      # $2 Bluetooth interface
      # $3 [amnesia minutes] (optional)

      # check if argument $2 empty
      if [[ -z "$2" ]] || [[ "$2" == -* ]];
      then
        echo "ERROR: invalid argument '${2}' for option ${1}!"
        print_usage
	exit 1
        break
      fi
      
      # check if option is remove
      if [[ "$2" == "remove" ]];
      then

        remove_service $SERVICE_NODE_BT

      else

        intf_bt="$2"

        # check optional argument $3
        if [[ -z "$3" ]] || [[ "$3" == -* ]];
        then
          bt_amnesia="";
        else
          bt_amnesia="$3";
          shift
        fi
        
        if create_service ${SERVICE_NODE_BT} ;
        then
          write_service_bt
        fi
      fi

      shift
      ;;
    
    *)
      echo "ERROR: option $1 unknown!"
      print_usage
      exit 1
      break
      ;;
  esac
  shift
done

