#!/usr/bin/env python2.5
# -*- coding: utf-8 -*-

"""
Copyright(C) 2009  Romain Bignon

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, version 3 of the License.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

"""

from __future__ import with_statement

import mechanize
import sys, tty, termios
import os
from optparse import OptionParser
from ConfigParser import SafeConfigParser, NoSectionError

class Application:

    CONFIG_FILE = '%s/.geoloc' % os.path.expanduser("~")

    def getparser(self):
        config = SafeConfigParser()

        login = ''
        try:
            config.read(self.CONFIG_FILE)
            login = config.get('auth', 'login')
        except (NoSectionError, ValueError), e:
            pass

        parser = OptionParser(usage="%prog [options] <IP address>")
        parser.add_option('-l', '--login', help="account ID", type="str", default=login)
        parser.add_option('-p', '--password', help="account password", type="str")
        return parser

    def prompt_password(self, prompt):
        sys.stdout.write(prompt)

        attr = termios.tcgetattr(sys.stdin)
        tty.setcbreak(sys.stdin)

        line = sys.stdin.readline().split('\n')[0]

        termios.tcsetattr(sys.stdin, termios.TCSAFLUSH, attr)
        sys.stdout.write('\n')

        return line

    def main(self, argv):
        parser = self.getparser()
        options, arguments = parser.parse_args()
        if not options.login or not arguments:
            parser.print_help()
            sys.exit(1)

        self.options = options

        if not self.options.password:
            self.options.password = self.prompt_password('Password: ')

        config = SafeConfigParser()
        config.add_section('auth')
        config.set('auth', 'login', self.options.login)
        with open(self.CONFIG_FILE, 'wb') as configfile:
            config.write(configfile)

        browser = mechanize.Browser()
        content = browser.open("http://www.geolocalise-ip.com/api.php?email=%s&pass=%s&ip=%s" %
                                            (options.login,
                                             options.password,
                                             arguments[0]))
        tab = content.read().split('&')
        for line in tab:
            key, value = line.split('=')
            print '%-20s %s' % (key, value)

        return 0

if __name__ == '__main__':
    app = Application()
    sys.exit(app.main(sys.argv))



