#!/usr/bin/env python
""" bibwatch: watch for changes to bibtex files and update Unite bibtex cache

Author    : Mark Sprevak <mark.sprevak@ed.ac.uk>
Copyright : Copyright 2015, Mark Sprevak
License   : BSD3
"""
import argparse
import bibtex
import cache
import datetime
import os
import sys
import time

VERSION = "0.1"
SLEEP_TIME = 1

DESCRIPTION = '''
bibwatch: watch for changes to BibTeX files and update their Unite BibTeX cache
'''

EPILOG = '''
Copyright (C) 2015 Mark Sprevak
Web:  http://sites.google.com/site/msprevak
This is free software; see the source for copying conditions. There is no
warranty, not even for merchantability or fitness for a particular purpose.
'''

def main():
    # initialise dictionaries
    c = dict()
    mtime_last = dict()
    mtime_cur = dict()
    # read command line arguments
    cli_args = parse_cli()
    bib_files = cli_args['input']
    cache_dir = cli_args['cache']
    if not bib_files:
        print('No BibTeX files listed on command line to monitor')
        exit(1)
    if not cache_dir:
        print('No cache directory specified on command line')
        exit(2)
    # check if cache is up to date
    for b in bib_files:
        print('monitoring: "%s"' % b)
        c[b] = cache.Cache(b, cache_dir)
        mtime_last[b] = 0
        try:
            c[b].read()
            mtime_last[b] = c[b].timestamp
        except (cache.NoCache, cache.OutdatedCache):
            mtime_last[b] = 0
    print('cache directory: "%s"' % cache_dir)
    print('(press Control+C to stop monitoring)')
    # monitor for changes
    try:
        while True:
            for b in bib_files:
                mtime_cur[b] = os.path.getmtime(b)
                if mtime_cur[b] != mtime_last[b]:
                    update(c[b])
                mtime_last[b] = mtime_cur[b]
                time.sleep(SLEEP_TIME)
    except KeyboardInterrupt:
        print('\nStopped')

def update(c):
    today = datetime.date.today().isoformat()
    now = datetime.datetime.now().time().isoformat()
    print(today + ' ' + now)
    print('    updating cache for "%s"' % c.source_path)
    start_time = time.time()
    c.update(bibtex.parse)
    c.write()
    elapsed_time = time.time() - start_time
    time_report = 'time taken: %s (%f seconds)' % (str(datetime.timedelta(seconds=elapsed_time)), elapsed_time)
    print('    written "%s"' % c.cache_path)
    print('-- done (%s)' % time_report)

def parse_cli():
    p = argparse.ArgumentParser(
        description=DESCRIPTION,
        epilog=EPILOG,
        formatter_class=argparse.RawTextHelpFormatter,
        add_help=False)
    p.add_argument('input', nargs='*',
                   help="BibTeX files to monitor for changes")
    p.add_argument("-h", "--help", '---help', '---h',
                   action="help",
                   help="show this help message and exit")
    p.add_argument('-v', '--version', '---version', '---v',
                   action='version',
                   version=('%(prog)s ' + VERSION))
    p.add_argument("--cache", '-c',
                    help='cache directory to write cached files')
    known_raw, unknown = p.parse_known_args()
    known = vars(known_raw)
    return known

if __name__ == '__main__':
    main()


@@ -846,16 +846,53 @@
 i()%0A    
+if not cli_args:%0A        exit(1)%0A    
 bib_file
@@ -947,217 +947,25 @@
 cach
-e'%5D%0A    if not bib_files:%0A        print('No BibTeX files listed on command line to monitor')%0A        exit(1)%0A    if not cache_dir:%0A        print('No cache directory specified on command lin
 e'
-)
+%5D
 %0A    
-    exit(2)%0A
+try:%0A    
     
@@ -995,24 +995,28 @@
 to date%0A    
+   
+ 
 for b in bib
@@ -1015,32 +1015,36 @@
 b in bib_files:%0A
+    
         print('m
@@ -1069,24 +1069,28 @@
  b)%0A        
+  
+  
 c%5Bb%5D = cache
@@ -1106,24 +1106,28 @@
  cache_dir)%0A
+    
         mtim
@@ -1144,29 +1144,37 @@
 = 0%0A        
+    
 try:%0A
+    
             
@@ -1185,16 +1185,20 @@
 .read()%0A
+    
         
@@ -1236,24 +1236,28 @@
 amp%0A        
+ 
+   
 except (cach
@@ -1289,16 +1289,20 @@
 Cache):%0A
+    
         
@@ -1319,24 +1319,28 @@
 last%5Bb%5D = 0%0A
+    
     print('c
@@ -1374,24 +1374,28 @@
 he_dir)%0A    
+  
+  
 print('(pres
@@ -1428,16 +1428,20 @@
 ring)')%0A
+    
     # mo
@@ -1460,31 +1460,22 @@
 anges%0A  
-  try:%0A
       
-  
 while Tr
@@ -1652,32 +1652,36 @@
                 
+    
 mtime_last%5Bb%5D = 
@@ -1693,16 +1693,20 @@
 _cur%5Bb%5D%0A
+    
         
@@ -1792,16 +1792,171 @@
 topped')
+%0A    except cache.MissingSource:%0A        print('ERROR: file not found')%0A    except cache.MissingCacheDir:%0A        print('ERROR: cache directory not found')
 %0A%0Adef up
@@ -2684,35 +2684,16 @@
 rgs='*',
-%0A                  
  help=%22B
@@ -2782,35 +2782,16 @@
  '---h',
-%0A                  
  action=
@@ -2916,35 +2916,16 @@
  '---v',
-%0A                  
  action=
@@ -3022,36 +3022,16 @@
 %22, '-c',
-%0A                   
  help='c
@@ -3119,21 +3119,20 @@
 s()%0A    
-known
+args
  = vars(
@@ -3150,20 +3150,304 @@
     
-return known
+if not args%5B'input'%5D:%0A        print('ERROR: No BibTeX files listed on command line to monitor%5Cn')%0A        p.print_help()%0A        return None%0A    if not args%5B'cache'%5D:%0A        print('ERROR: No cache directory specified on command line%5Cn')%0A        p.print_help()%0A        return None%0A    return args
 %0A%0Aif

add more warnings to bibwatch