#!/usr/bin/env python3

# Copyright 2012-4, Sean B. Palmer
# Source: http://inamidst.com/saxo/

import json
import re
import urllib.parse

import saxo

r_url = re.compile(r'(?ims)class="r".*?<a href="(.*?)"')
user_agent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:26.0) " + \
    "Gecko/20100101 Firefox/26.0"

@saxo.pipe
def g(arg):
    if not arg:
        return "Search for a phrase on Google"

    page = saxo.request("https://www.google.com/search",
        query={"q": arg},
        headers={"User-Agent": user_agent})

    for url in r_url.findall(page["text"]):
        if url.startswith("/"):
           continue
        return urllib.parse.unquote(url)
    return "No result for %s" % arg
