#!/usr/bin/env python

import cPickle
import os
import random
import sys

BQ_DIR = '/Users/dsorber/.bashquote'
BQ_CACHE = '/Users/dsorber/.bashquote/bq_cache'

def main():

    # Create the cache file, or open it if it already exists    
    if not os.path.exists(BQ_CACHE):
        print 'bashquote cache does not exist!'
        sys.exit()
    else :
        cache = open(BQ_CACHE, 'r')
        quotes = cPickle.load(cache)
        cache.close()

    # Choose a random quote from the list
    num_quotes = len(quotes)
    if num_quotes == 1:
        # Repopulate the list manually if there is only one quote remaining
        print 'Low on quotes, grabbing some more...',
        os.system('bashquote_populate')
        print 'Done'
    index = random.randint(0, num_quotes - 1)
    quote = quotes.pop(index)
    
    # Print it out
    print 'bashquote #%s ------ %s' % (quote[0], quote[1])
    print quote[2]

    # Re-store the remaining quotes and exit
    cache = open(BQ_CACHE, 'w')
    cPickle.dump(quotes, cache, -1)
    cache.close()
    sys.exit()

if __name__=="__main__":
    main()