#! /usr/bin/env bash
#
# geoiptool
#
# A quick and dirty shell script to easily extract data from geoiptool.com.
# Use, modify, copy, steal, and/or plunder this command to your hearts
# content, at your own risk of course :) --jimeh
#

padlen=13
ipaddress="$1"

if [[ "$1" == "--raw" ]] || [[ "$1" == "-r" ]]; then
  padlen=0
  ipaddress=$2
elif [[ "$2" == "--raw" ]] || [[ "$2" == "-r" ]]; then
  padlen=0
fi

case "$1" in
  "-h" | "--help")
    echo "usage: geoiptool [<ipaddress>]"
    echo ""
    echo "Options:"
    echo "  --raw, -r:  Do not align headers. Allows easier machine parsing of output."
    echo ""
    echo "Look up details for given IP address via http://www.geoiptool.com/. If no IP"
    echo "address is given, your own public IP will be used instead."
    ;;
  *)
    curl -s "http://www.geoiptool.com/en/?IP=${ipaddress}" -H "User-Agent: " |
      awk -F '(</?[^>]+>)+' \
        "/Host Name/,/Latitude/ {
          if (/:/) {
            printf(\"%${padlen}s \", \$2);
            getline;
            gsub(/^[ \t]+/, \"\", \$2);
            gsub(/[ \t]+$/, \"\", \$2);
            print \$2
          }
        }"
    ;;
esac
