#!/bin/bash

LOG="/var/log/syncthing-relaysrv.log"
declare -a CONNECTION
declare -a DOMESTIC_CONNECTION
declare -A IP_CACHE
cnt=0
same_cnt=0
MY_CTRY="Switzerland"
DEBUG=false

function geoiplookup64() {
	local ip="$1"
	local ctry="${IP_CACHE[$ip]}"

	if [ -z "$ctry" ]; then

		# determine ip version
		if [[ $ip == *':'* ]]; then
			GEOIPLOOKUP="geoiplookup6"
		else
			GEOIPLOOKUP="geoiplookup"
		fi

		# lookup
		ctry="$("$GEOIPLOOKUP" "$ip" | sed -e "s/^GeoIP Country\( V6\)\{0,1\} Edition: //" -e "s/^IP Address not found/unknown/" -e "s/^can't resolve hostname/unknown/" -e "s/.., //")"
		IP_CACHE["$ip"]="$ctry"
	else
		$DEBUG && cache_hit=$((cache_hit+1))
	fi

	# give country back as variable passed in arg 2
	printf -v "$2" -- "$ctry"
}

# get log from arglist
if [[ -n "$1" && -f "$1" ]]; then
	LOG="$1"
fi

while read -r line; do
	sip="$(echo "$line" | sed -e "s/ <> .*$//" -e "s/:[0-9]\+$//" -e "s/^\[//" -e "s/]$//")"
	geoiplookup64 "$sip" SRC

	dip="$(echo "$line" | sed -e "s/^.* <> //" -e "s/:[0-9]\+$//" -e "s/^\[//" -e "s/]$//")"
	geoiplookup64 "$dip" DEST

	if [[ "${SRC}" = "${DEST}" ]]; then
		same_cnt=$((same_cnt+1))
		DOMESTIC_CONNECTION[$cnt]="$SRC - $DEST"
	elif [[ "${SRC}" < "${DEST}" ]]; then
		CONNECTION[$cnt]="$SRC - $DEST"
	else
		CONNECTION[$cnt]="$DEST - $SRC"
	fi
	cnt=$((cnt+1))
done <<< $(zgrep --binary-files=text "session.go:[0-9]*: Session .* starting between " "$LOG" | sed -e "s/^.*: Session .* starting between //g" -e "s/ and / <> /" | sort -n | uniq)

# print connections
echo
echo "Sessions from or to $MY_CTRY ($(printf "%s\n" "${CONNECTION[@]}" | grep -c "$MY_CTRY")):" ; echo
printf "%s\n" "${CONNECTION[@]}" | grep "$MY_CTRY" | sort | uniq -c | sort -rn
echo
echo
echo "Foreign international sessions ($(printf "%s\n" "${CONNECTION[@]}" | grep -vc "$MY_CTRY")):" ; echo
printf "%s\n" "${CONNECTION[@]}" | grep -v "$MY_CTRY" | sort | uniq -c | sort -rn
echo
echo
echo "Domestic sessions ($same_cnt):" ; echo
printf "%s\n" "${DOMESTIC_CONNECTION[@]}" | sed -e "s/ - .*$//g" | sort | uniq -c | sort -rn
echo
echo

# show summary
echo "$((same_cnt * 100 / cnt))% of all sessions are domestic ($same_cnt/$cnt)."
$DEBUG && echo "Cache hits: $cache_hit"

exit 0
