#!/bin/bash

set -e

REMOVE=false

function usage() {
  printf "%s [options]\n" "$(basename "$0")"
  printf "\toptions\n"
  printf "\t-h this help\n"
  printf "\t-r remove unknown callids from redis properly\n"
}

while getopts "rh" opt; do
  case $opt in
    h) usage; exit 0;;
    r) REMOVE=true;;
    \?) usage; exit 1;;
  esac
done
shift $((OPTIND-1))

if [[ $# -ne 0 ]] ; then
  usage
  exit 2
fi

if ! ngcp-check-active -q ; then
  echo "node is not active, abort" >&2
  exit 3
fi

# read kamailio.proxy.dlgcnt.pair_redis_db
REDIS_DB="$(ngcp-dlgcnt-clean -c fake 2>/dev/null|| echo 4)"
host="$(ngcp-dlgcnt-clean -C fake 2>/dev/null|| echo localhost)"

# redis full list
REDIS_CALLIDS=$(mktemp)
ngcp-redis-helper -h "$host" -n "$REDIS_DB" dumps | grep -E -v "^$" > "$REDIS_CALLIDS" || true

# kamailio full dialogs (no ngcp-kamcmd because in fails in case of large output)
KAMAILIO_DIALOGS=$(mktemp)
ngcp-kamctl proxy fifo dlg.list | awk '/"call-id":/ { print $NF}' > "$KAMAILIO_DIALOGS" || true

# 'lists:' belongs to dlglist
REDIS_CALLIDS_FILTER=$(mktemp)
grep -E -v '^\s+"list:' "$REDIS_CALLIDS" > "$REDIS_CALLIDS_FILTER" || true

while read -r i ; do
  if [[ "$i" == '[' || "$i" == ']' || "$i" == "Database is empty" ]]; then
		continue
	fi
  # remove from the existing string any comma or quote that could come from a json formatting
  id=$(echo "$i" | tr -d ',\"')
  if ! grep -q -- "$id" "$KAMAILIO_DIALOGS"
  then
    printf "CallID:[%s] unknown\n" "$id"
    if $REMOVE ; then
      ngcp-dlgcnt-clean "--" "$id" || true
      if grep -q "list:$id" "$REDIS_CALLIDS" ; then
        ngcp-dlglist-clean "--" "$id" || true
      fi
    fi
  fi
done < "$REDIS_CALLIDS_FILTER"

rm -f "$KAMAILIO_DIALOGS" "$REDIS_CALLIDS" "$REDIS_CALLIDS_FILTER"
