#!/usr/bin/env python3

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

import json
import re
import urllib.parse

import saxo

r_url = re.compile(r'(?ims)/url[?]q=([^&]+)')

@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={"Referer": "https://www.google.com/"})

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