#!/bin/bash
#
#
LANGUAGE=en
DATABASE_PATH=/var/lib/GeoIP2

help() {
  echo "Usage: $0 [OPTION]...IP"
  echo
  echo "  -f, --full    Full country name"
  echo
}

FULL=
POSITIONAL=()
while [[ $# -gt 0 ]]
do
  key="$1"

  case $key in
    -f|--full)
    FULL=1
    shift # past argument
    ;;
    -h|--help)
    help
    exit 0
    ;;
    *)    # unknown option
    POSITIONAL+=("$1") # save it in an array for later
    shift # past argument
    ;;
  esac
done
set -- "${POSITIONAL[@]}" # restore positional parameters

if [ -z "$1" ] ; then
  echo "No IP number"
  echo
  help
  exit 1
else
  IP=$1
fi

#
# Country name
#
if [ -z "$FULL" ] ; then
  #
  # ISO name
  #
  COUNTRY=`mmdblookup -f $DATABASE_PATH/GeoLite2-City.mmdb -i $IP country iso_code | grep '"' | cut -d'"' -f 2`
else
  #
  # Full name
  #
  COUNTRY=`mmdblookup -f $DATABASE_PATH/GeoLite2-City.mmdb -i $IP country names $LANGUAGE | grep '"' | cut -d'"' -f 2`
fi

#
# City
#
CITY=`mmdblookup -f $DATABASE_PATH/GeoLite2-City.mmdb -i $1 city names $LANGUAGE 2>/dev/null | grep '"' | cut -d'"' -f 2`

#
# Output
#
if [ -z "${CITY}" ] ; then
  echo ${COUNTRY}
else
  echo ${CITY}", "${COUNTRY}
fi

#
# Done
#
exit 0
