#! /usr/bin/python

'''ptfind 0.3.3 -- shell command for submitting Pathena queries

Use ptfind to run queries against the Pathena Desktop Search database.
Results are returned on standard output.

Usage: ptfind [-a] [-q] [-s] [-v] [-h] [term ...]

Options:
  -a   --all        Don't filter out nonexistent paths from result.
  -q   --quote      Add quotes around paths returned.
  -s   --status     Print database status and exit.
  -v   --version    Print the version number and exit.
  -h   --help       Print this message.

Arguments:
  term ...          Search terms for submission to Pathena server.
  'text_term ...; path_term ...; date; type'      Fully qualified form.
'''

import os, sys, time

base = os.path.expandvars('$PATHENA')
for dir in ('lib',):
    sys.path.insert(0, os.path.join(base, dir))

import getopt

from StringIO import StringIO
from traceback import print_exc

from app_globals import *


def usage(code, msg=''):
    if code == 1: channel = sys.stdout
    else:         channel = sys.stderr
    print >> channel, __doc__  # docstring()
    if msg: print >> channel, msg
    sys.exit(code)

def main():
    all_paths, quote = 0, 0
    try:
        opts, args = getopt.getopt(
            sys.argv[1:],
            'aqsvh',
            ['all', 'quote', 'status', 'help', 'version'])
    except getopt.GetoptError, msg:
        usage(2, msg)

    for opt, arg in opts:
        if opt in ('-h', '--help'):
            usage(1)
        elif opt in ('-v', '--version'):
            print 'ptfind (Pathena) %s' % app_version
            sys.exit(0)
        elif opt in ('-q', '--quote'):
            quote = 1
        elif opt in ('-a', '--all'):
            all_paths = 1
        elif opt in ('-s', '--status'):
            from db_connect import getServerStatus
            show_status(getServerStatus())
            sys.exit(0)

    # now perform query
    from submit_query import perform_query
    query_result = perform_query(split_and_pad_terms(' '.join(args)))[1]
    if not query_result:            # empty result
        sys.exit(0)
    result = [ r[1] for r in query_result ]
    if not all_paths:
        result = filter(os.path.exists, result)
    if quote:
        for r in result: print '"%s"' % r
    else:
        for r in result: print r


def show_status(status):
    if status:
        status_msg = \
            'Pathena Server is up and running on %%s\n' \
            'under the control of a PostgreSQL postmaster process.\n\n' \
            '    Postmaster process id:           %8s\n' \
            '    Listening on port:               %8s\n' \
            '    Approximate database size (MB):  %8s\n' \
            '    PostgreSQL cluster size (MB):    %8s\n' \
            '    Paths indexed in the database:   %8s\n' \
            '    Files having full text indexing: %8s\n' \
            '    Files cached in the database:    %8s\n' \
            % status
    else:
        status_msg = 'Pathena Server is not running on %s.'
    print status_msg % time.asctime()

connect_fail_msg = \
'''Connection failure: the Pathena database server did not respond.
Attempts to restart the server process were unsuccessful.  It's
possible an earlier instance of the server was not shut down properly.
Try running 'tail ~/.pathena/log/pg_server' for information about
possible server startup problems.
'''

database_error_msg = \
'''Database error: the Pathena database server encountered an error
while processing this query.  Try the query again.  If problems
persist, try restarting the server.
'''

try:
    exit_code = 0
    main()
except SystemExit:
    pass
except SearchTermError:
    exit_code = 1
    pass
except ConnectionFailure:
    exit_code = 2
    print >> sys.stderr, connect_fail_msg
except DatabaseError:
    exit_code = 3
    print >> sys.stderr, database_error_msg
except:
    exit_code = 10
    trace = StringIO()
    print_exc(1, trace)
    print >> sys.stderr, trace.getvalue()

sys.exit(exit_code)
