import sys
import ip2location

def usage():
    print """
getRangesForCity.py

NAME

 getRangesForCity.py - Give the name of any city in the world and it will return a list of IP ranges (int form) that exist within that city.

SYNOPSIS
   python getRangesForCity.py [options] <NAME OF REGION> <NAME OF CITY> <FORMAT=plain>

   <NAME OF REGION> - The name of the region to where the city belongs

   <NAME OF CITY> - The name of any city in the world

   <FORMAT>       - This will determine how the output will look like.

                    Valid formats are:
                      plain (default)
                      php
                      python

                    If enter an invalid format, the plain format will be used by default

  Options:
  -h, --help      - Shows this help

AUTHOR
Written by Angel Leon. June 2008. angel.leon@frostwire.com
"""

VALID_FORMATS = ("plain","php","python")

def formatRanges(ranges,format="plain"):
    result = ""

    if format not in VALID_FORMATS:
        format="plain"

    if format == "python":
        return "ipRanges = " + str(ranges)

    if format == "php":
        result = "$ipRanges = array("

    for r in ranges:
        if format=="plain":
            result += "\t"+str(r[0])+","+str(r[1])+"\r\n"
        elif format=="php":
            result += "array("+str(r[0])+","+str(r[1])+"), "

    if format == "php":
        result += ");"

    return result

REGION=None
CITY=None
FORMAT="plain"

if __name__ == "__main__":
    if len(sys.argv) < 2 or "-h" in sys.argv or "--help" in sys.argv:
        usage()

    print sys.argv

    if len(sys.argv) > 2:
        REGION=sys.argv[1].upper()
        CITY=sys.argv[2].upper()

    if len(sys.argv)>3:
        FORMAT=sys.argv[3].lower()

    print "Getting ranges for %s, %s" % (CITY,REGION)
    print "Please wait, this could take a few minutes..."

    RANGES = ip2location.getRangesForCity(REGION,CITY)

    if RANGES == None or len(RANGES) == 0:
        print "No IP ranges were found for %s" % CITY
        sys.exit(1)

    formattedRanges = formatRanges(RANGES,FORMAT)

    print len(RANGES),"ranges where found for %s,%s" % (CITY,REGION),"\n"
    print formattedRanges
