#!/usr/bin/env python3
#
# Adds DuckDuckGo bang as searchengine.
#
# Usage:
#   :spawn --userscript ripbang [bang]...
#
# Example:
#   :spawn --userscript ripbang amazon maps
#

import os, re, requests, sys
from urllib.parse import urlparse, parse_qs

for argument in sys.argv[1:]:
    bang = '!' + argument
    r = requests.get('https://duckduckgo.com/',
                     params={'q': bang + ' SEARCHTEXT'},
                     headers={'user-agent': 'qutebrowser ripbang'})

    searchengine = re.search("url=([^']+)", r.text).group(1)
    searchengine = urlparse(searchengine).query
    searchengine = parse_qs(searchengine)['uddg'][0]
    searchengine = searchengine.replace('SEARCHTEXT', '{}')

    if os.getenv('QUTE_FIFO'):
        with open(os.environ['QUTE_FIFO'], 'w') as fifo:
            fifo.write('config-dict-add url.searchengines %s %s' % (bang, searchengine))
    else:
        print('%s %s' % (bang, searchengine))
