#!/bin/bash

# use "--all" to see all active nodes

ETC=/opt/natp-ssh/etc

cd ${ETC}

ALL=""
if [ "$1" = "--all" ] ;then
  ALL="true"
fi

if [ ! -f explained.txt ] ;then
  cat <<EOM > explained.txt
# The following ark nodes are not expected to connect via natp-ssh
# node name, reason
xxx-yy,template node
EOM
fi

#ACTIVEARKNODES=$(curl -sX POST -H "Content-Type: application/json" --data "{\"query\": \"{ find_monitors(input: {state:ACTIVATED}) { monitors { name } } }\"}" https://dory.caida.org/graphql | perl -nle 'use JSON; $x=JSON::decode_json($_); for (@{$x->{"data"}{"find_monitors"}{"monitors"}}) { push @a, $_->{"name"} }; print join " ", sort @a')

ACTIVEARKNODES=$(curl -s \
  https://www.caida.org/projects/ark/locations/dynamic/ark-map-info.json \
  | /usr/bin/jq -M '.mons[] | [ .name , .status, .hardware ] | @csv' \
  | sed 's/[\\"]//g' | grep -v inactive | sed 's/,active.*//g' | sort)

DEFINEDNODES=$(sed 's/,.*$//' ${ETC}/vantage-points)
DEFINEDNODES=$(echo ${DEFINEDNODES}) # change end of lines to spaces
DEFINEDNODES=$(echo " ${DEFINEDNODES} ")

CONNECTED=$(ps auxww |grep natp-sshd: | grep -v priv | sort \
  | awk '{ print $1 }')
CONNECTED=$(echo ${CONNECTED}) # change end of lines to spaces
CONNECTED=$(echo " ${CONNECTED} ")

for node in ${ACTIVEARKNODES} ;do
  GREP=$(echo "${CONNECTED}" | grep " ${node} " )
  if [ "${GREP}" = "" ] ;then
    EXPLANATION=$(grep "^${node}," explained.txt | sed 's/^[^,]*,//')
    if [ "${EXPLANATION}" = "" ] ;then
      GREP=$(echo "${DEFINEDNODES}" | grep " ${node} " )
      if [ "${GREP}" = "" ] ;then
        echo "${node} active but not configured"
      else
        echo "${node} active and configured but not connected"
      fi
    else
      if [ "${ALL}" = "true" ] ;then
        echo "${node} not connected: ${EXPLANATION}"
      fi
    fi
  else
    if [ "${ALL}" = "true" ] ;then
      PROCESS=$(ps auxww |grep "${node}.*priv" |grep -v grep \
        | awk '{ print $2 }')
      PROCESS=$(echo $PROCESS)
      PORT=$(grep "^${node}," ${ETC}/vantage-points | awk -F, '{ print $2 }')
      PORT=$(echo $PORT)
      echo "${node} connected ssh port ${PORT} pid ${PROCESS}"
    fi
  fi
done
