#!/bin/bash
# @description run a debug _cf-serverd_ intended for a specific node
# @man This command targets a specific node and does not affect the running
# @man infrastructure.
# @man In *-l* mode, it looks for existing logs for the given node.
# @man In *-i* mode, it uses _iptables_ to redirect the specific node communications
# @man to the port the debug server is listening on (5310 by default).
# @man +
# @man Use Ctrl+C to stop the debug server.
# @man +
# @man *Arguments*:
# @man +
# @man *-l*: fetch debug logs for the given node
# @man +
# @man *-i*: run a debug server for the given node
# @man +
# @man *node*: IP or hostname of the host you want to debug

. "${BASEDIR}/../lib/common.sh"

DEBUG_PORT=5310
SERVER_PORT=$(cut -d: -s -f2 "${RUDDER_VAR}/cfengine-community/policy_server.dat")
SERVER_PORT=${SERVER_PORT:-5309}

set -e

# necessary to manage iptables removal on error or on ctrl-c
function anomaly_handler() {
  iptables -t nat -D PREROUTING -p tcp -s ${NODE} --dport ${SERVER_PORT} -j DNAT --to-destination :${DEBUG_PORT}
  echo ""
  echo "Debug has been stopped on step: ${STEP}"
  exit 1
}

# Parameter
STEP="INIT"

while getopts "i:l:" opt; do
  case $opt in
    i)
      MODE=iptables
      NODE="${OPTARG}"
      ;;
    l)
      MODE=log
      NODE="${OPTARG}"
      ;;
  esac
done

if is_https_only; then
  echo "HTTPS only mode is enabled. This command only handles the CFEngine protocol."
  exit 1
fi

if [ -z "${NODE}" ]
then
  echo "Usage rudder server debug [-i|-l] <node_ip>"
  exit 1
fi

if [ "${MODE}" = "iptables" ]
then
  trap anomaly_handler ERR INT TERM

  STEP="Creating redirect iptables rule"
  iptables -t nat -I PREROUTING -p tcp -s ${NODE} --dport ${SERVER_PORT} -j DNAT --to-destination :${DEBUG_PORT}

  STEP="Running debug server"
  ${RUDDER_DIR}/bin/cf-serverd -v --no-fork -D debug_port

  STEP="Removing iptables rule"
  iptables -t nat -D PREROUTING -p tcp -s ${NODE} --dport ${SERVER_PORT} -j DNAT --to-destination :${DEBUG_PORT}
else
  journalctl -f -xe -u rudder-cf-serverd | grep "${NODE}"
fi
