#!/bin/bash
# {{ ansible_managed }}

if [ $# -ne 1 ]; then
  echo "Usage: `basename $0` <ip>" 1>&2
  exit 0 # return true in case of config issue
fi

NETWORKS="{{ geoip_ssh_allowed_networks | join(" ") }}"
ALLOW_COUNTRIES="{{ geoip_ssh_allowed_zones | join(" ") }}"
GEOIPTOOL=$(which geoiplookup)

# Fetch the GitHub runner IP ranges
GITHUB_RUNNER_IP_RANGES=$(curl -s https://api.github.com/meta | jq -r '.actions[]')

# Priority: Check if the IP is a GitHub runner IP
if grepcidr "$GITHUB_RUNNER_IP_RANGES" <(echo "$1") >/dev/null; then
  logger "GitHub runner IP detected: $1"
  exit 0
fi

# Proceed with regular checks if it's not a GitHub runner IP

# All countries are allowed, only check CIDR
if [ "$ALLOW_COUNTRIES" = "ALL" ]; then 
  # Check if the IP is in allowed subnets
  logger "All countries allowed"
  grepcidr "$NETWORKS" <(echo "$1") >/dev/null && exit 0
fi

# Get the country of the IP using geoiplookup
COUNTRY=`$GEOIPTOOL $1 | awk -F ": " '{ print $2 }' | awk -F "," '{ print $1 }' | head -n 1`

# Check if the country is allowed
[[ $ALLOW_COUNTRIES =~ $COUNTRY ]] && RESPONSE="ALLOW" || RESPONSE="DENY"

if [ $RESPONSE = "ALLOW" ]; then
  # Check if the IP is in allowed subnets
  grepcidr "$NETWORKS" <(echo "$1") >/dev/null && exit 0
fi

logger "$RESPONSE sshd connection from $1 ($COUNTRY)"
exit 1
