#!/usr/local/bin/python

import ConfigParser
import MySQLdb
import re
import sys

def Shorten(url):
  db = SetupDb()
  cursor = db.cursor()
  selectsql = 'SELECT id FROM urlredirect WHERE url = "%s"' % url
  cursor.execute(selectsql)
  numrows = int(cursor.rowcount)
  if numrows > 0:
    row = cursor.fetchone()
    msg = row[0]
  else:
    insertsql = 'INSERT INTO urlredirect (url) VALUES ("%s")' % url
    cursor.execute(insertsql)
    msg = db.insert_id()
  return msg

def Expand(id):
  db = SetupDb()
  cursor = db.cursor()
  selectsql = 'SELECT url FROM urlredirect WHERE id = "%s"' % id
  cursor.execute(selectsql)
  numrows = int(cursor.rowcount)
  if numrows > 0:
    row = cursor.fetchone()
    url = row[0].tostring()
    return url
  else:
    return None

def SetupDb():
  db_config = ConfigParser.ConfigParser()
  db_config.readfp(open('config/database.conf'))
  db_unix_socket = db_config.get('database', 'db_unix_socket')
  db_username = db_config.get('database', 'db_username')
  db_password = db_config.get('database', 'db_password')
  db_name = db_config.get('database', 'db_name')
  db = MySQLdb.connect(unix_socket=db_unix_socket,
      user=db_username,
      passwd=db_password,
      db=db_name)
  return db

def MatchURL(msg):
  url_config = ConfigParser.ConfigParser()
  url_config.readfp(open('config/url_shorten.conf'))
  url_path = url_config.get('url', 'url_path')
  try:
    id = re.match(('.*%s([\d]+)' % url_path), msg).group(1)
  except AttributeError:
    pass
  else:
    long_url = Expand(id)
    if long_url == None:
        long_msg = 'No such shortened URL!'
    else:
      long_msg = 'URL expanded: %s' % long_url
    return long_msg
  try:
    url = re.match('.*(http://[\S]+)', msg).group(1)
  except AttributeError:
    pass
  else:
    if len(url) > 40:
      short_url = Shorten(url)
      short_msg = 'URL shortened: %s%s' % (url_path, short_url)
    else:
      return
    return short_msg

  # If we get to here, nothing else matched and we return None
  return None

def main():
  line = sys.argv[1]
  result = MatchURL(line)
  print result

if __name__ == '__main__':
  main()
