#!/usr/bin/env python

import sys, os
import string
import urllib

def isBeagleRunning():
    status = os.popen("beagle-ping", "r").read()
    return status.startswith("Daemon version:")

def formatHTML(query, hits):
    '''Format raw list of apps found, prints HTML formatted document on stdout
    
    @param query: the original query words
    @param hits: list of help:/ hits
    '''

    print "<html>\n"
    print "<body>"
    print "<ul>"

    for hit in hits:
        print "<li>" + hit + "</li>"

    print "</ul>\n</body>\n</html>\n"

def beagleQuery(words, method = 'and', maxnum = 100):
    '''Perform a beagle-query search.
    
    @param words: space separated query
    @param method: search method (AND, OR)
    @param maxnum: maximum number of hits returned
    
    @return a list of help:/ links separated by \n
    '''
    # Syntax: beagle-query --type DocbookEntry --max-hits=<maxnum> <words>
    hits = []
    pipe = os.popen("beagle-query --type DocbookEntry --type File --max-hits %s %s ext:docbook" % (maxnum, words), "r")

    if pipe:
        for line in pipe:
            uri = urllib.unquote(line.strip())
            uri = uri.replace("file://", "") # remove protocol
            #print uri
            helpLink = makeHelpLink(uri)
            if helpLink not in hits:
                hits.append(helpLink)

    pipe.close()
    return hits

def makeHelpLink(path):
    '''
    Try to figure out the name of the application from the path to its index.docbook file
    
    @param path: path to the .docbook file
    
    @return HTML-formatted help:/ link
    '''
    appName = path.split(os.sep)[-2]
    appName2 = path.split(os.sep)[-3]

    if (appName == appName2 or appName2 == "doc" or len(appName2) == 2):           # just the app
        return "<a href=\"help:/" + appName + "\">" + appName + "</a>"
    else:                               # things like kcontrol/colors
        return "<a href=\"help:/" + os.path.join(appName2, appName) + "\">" + appName + " (" + appName2 + ")</a>"

def main():
    import getopt
    try:
        opts, args = getopt.getopt(sys.argv[1:], "", ["method=", "maxnum="])
    except getopt.GetoptError:
        sys.exit("Command line syntax error")

    method = 'and'
    maxnum = 100
    docid = None
    words = None

    for o, a in opts:
        if o == "--method":
            method = a
        if o == "--maxnum":
            maxnum = a
    if args:
        words = args[0].replace('+', ' ') # replace + signs by spaces
    else:
        sys.exit("No search term specified")

    if (isBeagleRunning()):
        hits = beagleQuery(words, method, maxnum)
    else:
        hits = ["The Beagle daemon is not running, search is not available"]

    formatHTML(words, hits)

if __name__ == '__main__':
    main()
