aboutsummaryrefslogtreecommitdiff
path: root/bin/96btool
blob: c7489b82fd73fd83932d6115d6257ad2b01a7849 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
#!/usr/bin/env python3

'''
96btool - Tool to study a users forum posts

Prerequisites (ubuntu:16.04):

 * sudo apt -y install python3 python3-pip
 * sudo apt -y install python3-iso8601

Reminders of interesting threads for a weekly report:

    96btool pull --pipe | \
    96btool filter \
	--user danielt \
	--since 'next-friday -13 days' \
	--until 'next-friday -1 week' | \
    96btool weekly
'''

import argparse
import collections
import datetime
import iso8601
import json
import re
import subprocess
import sys
import pydiscourse
import os
import textwrap
import time
import traceback

import toys.chart as chart
import toys.collect as collect
import toys.config as config
import toys.date as date

# If it's installed we'd rather use IPython for interaction...
try:
	import IPython
	interact = IPython.embed
except:
	import pdb
	interact = pdb.set_trace

# To keep this up-to-date try:
#   filter --grep "About the.*category"
category_lookup = {
	1: 'Uncategorized',
	4: 'Staff',
	5: 'General',
	6: 'Specification',
	7: 'Products',
	9: 'HiKey',
	10: 'DragonBoard410c',
	11: 'Bubblegum-96',
	13: 'MediaTek-X20',
	15: 'Carbon',
	16: 'Poplar Board',
	17: 'Mezzanine Support',
	18: 'OpenHours',
	19: 'DragonBoard820c',
        20: 'Linaro Staff',
        21: 'Hikey 960',
        22: 'Nitrogen',
        23: 'OrangePi i96',
        24: 'iMX7-96',
}

def load_json(obj):
	if not obj:
		return json.load(sys.stdin)

	if isinstance(obj, str):
		with open(obj, 'r') as f:
			return json.load(f)

	return json.load(obj)

class Post(dict):
	post_db = {}
	topic_db = {}
	username_db = {}
	user_db = {}

	def created_at(self):
		return iso8601.parse_date(self['created_at'])

	def get_user(self, client):
		if self['username'] not in Post.user_db:
			time.sleep(0.1)
			Post.user_db[self['username']] = client.user(self['username'])
		self['user'] = Post.user_db[self['username']]
		return self['user']

	def lint(self):
		'''Fix minor errors and inefficiencies with a post.

		Returns true of the entire post should be discarded.
		'''
		if 'user' in self:
			Post.lint_user(self['user'])

		if 'topic' in self:
			Post.lint_topic(self['topic'])

			# Many Linaro staff are admins with access to PMs but we
			# never want to make local copies of these. This is
			# mostly respect for privacy although, in truth, they
			# would also confuse the statistics!
			return self['topic']['archetype'] == 'private_message'

		return False

	@staticmethod
	def fetch(client, from_id, to_id, verbose=False):
		for post_id in range(from_id, to_id):
			try:
				time.sleep(0.5)
				post = client._get('/posts/{}.json'.format(post_id))
				post = Post(post)
				if post.lint():
					if verbose:
						sys.stdout.write('P')
						sys.stdout.flush()
					continue

			except pydiscourse.exceptions.DiscourseClientError:
				if verbose:
					sys.stdout.write('E')
					sys.stdout.flush()
				continue

			result = '.'

			if post['topic_id'] not in Post.topic_db:
				time.sleep(0.1)
				try:
					topic = client._get(
						'/t/{}.json'.format(
							post['topic_id']))
				except pydiscourse.exceptions.DiscourseClientError:
					if verbose:
						sys.stdout.write('T')
						sys.stdout.flush()
					continue
				result = 'o'
			else:
				topic = Post.topic_db[post['topic_id']]
			post['topic'] = topic

			try:
				post.get_user(client)
			except pydiscourse.exceptions.DiscourseClientError:
				if verbose:
					sys.stdout.write('U')
					sys.stdout.flush()

			post.lint()
			post.index(post)

			if verbose:
				sys.stdout.write(result)
				sys.stdout.flush()

	@staticmethod
	def index(posts):
		if isinstance(posts, Post):
			posts = (posts,)
		for p in posts:
			Post.post_db[p['id']] = p
			if 'topic' in p:
				Post.topic_db[p['topic_id']] = p['topic']
			if 'username' in p:
				Post.username_db[p['user_id']] = p['username']
			if 'user' in p:
				Post.user_db[p['user_id']] = p['user']

	@staticmethod
	def latest(client):
		# Grab the latest topics (we can use these to figure out the
		# most recent post_id)
		latest_topics = client.latest_topics()

		# Although the 0th topic is normally the freshest there
		# are some conditions where pinned topics are listed at
		# the top of the list despite being pretty old (this
		# is a particular problem when the user is not logged in)
		latest_topic = max(latest_topics['topic_list']['topics'],
				   key=lambda k: k['last_posted_at'])
		latest_topic_id = latest_topic['id']
		latest_topic = client._get('/t/{}.json'.format(latest_topic_id))
		latest_post_id = max(latest_topic['post_stream']['stream'])

		# Having downloaded it we may as well cache it
		Post.lint_topic(latest_topic)
		Post.topic_db['latest_topic_id'] = latest_topic

		return latest_post_id

	@staticmethod
	def lint_topic(t):
		if 'post_stream' in t:
			del t['post_stream']
		if 'details' in t:
			del t['details']
		if 'category' not in t:
			t['category'] = 'UNKNOWN'
		if t['category'] == 'UNKNOWN':
			if not t['category_id']:
				t['category'] = 'None'
			elif t['category_id'] in category_lookup:
				t['category'] = category_lookup[t['category_id']]
			else:
				print('WARNING: Unknown category id: {}'.format(
						t['category_id']),
						file=sys.stderr)
				t['category'] = 'UNKNOWN'
		if 'username' not in t or t['username'] == 'unknown':
			if t['user_id'] in Post.username_db:
				t['username'] = Post.username_db[t['user_id']]
			else:
				t['username'] = 'unknown'
		if 'uri' not in t:
			t['uri'] = 'https://discuss.96boards.org/t/{}'.format(
					t['slug'])

		return t

	@staticmethod
	def lint_user(u):
		'''Drop all info about a user except for a narrow whitelist'''
		keep = ( 'email', 'id', 'name', 'username', 'website' )
		for k in list(u):
			if k not in keep:
				del u[k]
		return u

	@staticmethod
	def load(obj):
		return [ Post(p) for p in load_json(obj) ]

def do_chart(args):
	'''Visualise the post data as a stacked bar chart'''
	posts = Post.load(args.json)

	title = args.title if args.title else 'Posts by month and category'

	if args.by_tag:
		by_month_by_xxx = collect.accumulate_2d(posts,
			lambda p: iso8601.parse_date(p['created_at']).strftime('%Y-%m'),
			lambda p: ','.join(p['tags']))
	else:
		by_month_by_xxx = collect.accumulate_2d(posts,
			lambda p: iso8601.parse_date(p['created_at']).strftime('%Y-%m'),
			lambda p: p['topic']['category'])

	chart.stacked_barchart(by_month_by_xxx, args.output,
			title = title, ylabel = 'Number of posts')

def do_count(args):
	'''Count posts, potential organising them into categories first'''
	posts = Post.load(args.json)
	count = None

	if args.by_category:
		count = collect.accumulate(posts,
				lambda x: x['topic']['category'])

	if args.by_user:
		count = collect.accumulate(posts, lambda x: x['username'])
		if None in count:
			del count[None]

	if count:
		if args.simplify:
			remaining = collect.simplify(count)

		flat_count = [ (k, v) for k, v in count.items() ]
		if args.rank:
			flat_count = sorted(flat_count, key=lambda x: x[1], reverse=True)
		else:
			flat_count = sorted(flat_count, key=lambda x: x[0])

		if args.simplify:
			flat_count.append(('Other', remaining))

		if args.csv:
			for k, v in flat_count:
				print('"{}",{}'.format(k, v))
		elif args.text:
			for k, v in flat_count:
				print('{:30} {}'.format(k, v))
		else:
			if args.rank:
				count = flat_count
			json.dump(count, sys.stdout, sort_keys=True, indent=2)
	else:
		print(len(posts))

def do_dump(args):
	'''Dump the local database to standard output'''
	with open(args.db) as f:
		sys.stdout.write(f.read())

def do_fetch(args):
	'''Use discourse to search for matching topics (limited to <50)'''
	since = date.smart_parse(args.since)
	after = since.strftime(' after:%Y-%m-%d')

	cfg = config.get_config()
	client = pydiscourse.DiscourseClient( cfg['96btool']['server'],
			api_username=cfg['96btool']['username'],
			api_key=config.get_password(cfg, '96btool'),
			timeout=5)

	results = client._get('/search.json', **{ 'q': args.query + after })

	posts = results['posts']
	if len(posts) == 50:
		print("Too many results, limited to 50", file=sys.stderr)

	topics = {}
	for post in posts:
		topic_id = post['topic_id']
		if topic_id not in topics:
			topic = client._get('/t/{}.json'.format(topic_id))
			del topic['post_stream']
			del topic['details']
			topics[topic_id] = topic
		post['topic'] = topics[topic_id]

	# Sort by date
	posts = sorted(posts, key=lambda k: k['created_at'])

	json.dump(posts, sys.stdout, indent=2)

def do_filter(args):
	'''Filter posts using various criteria (including date of post)'''
	since = date.smart_parse(args.since)
	until = date.smart_parse(args.until)

	posts = Post.load(args.json)

	posts = [ p for p in posts if iso8601.parse_date(p['created_at']) >= since ]
	posts = [ p for p in posts if iso8601.parse_date(p['created_at']) < until ]

	if args.tag:
		posts = [ p for p in posts if 'tags' in p and args.tag in p['tags'] ]

	if args.user:
		users = args.user.split(',')
		posts = [ p for p in posts if p['username'] in users ]


	if args.first_post:
		# Opps. We stripped out the post stream so this test ends up more
		# complex than it needs to be...
		def is_first_post(p):
			# If the topic was created by a different user
			# this cannot be the first post
			if p['username'] != p['topic']['username']:
				return False

			# If the post was made >10 seconds after the topic was created
			# then its not the first post either.
			topic_created_at = iso8601.parse_date(p['topic']['created_at'])
			cut_off_time = topic_created_at + datetime.timedelta(seconds=10)
			post_created_at = p.created_at()
			return post_created_at < cut_off_time

		posts = [ p for p in posts if is_first_post(p) ]

	if args.category:
		categories = args.category.lower().split(',')
		def matched(p):
			category = p['topic']['category'].lower()
			for c in categories:
				if c in category:
					return True

			return False

		posts = [ p for p in posts if matched(p) ]

	if args.grep:
		e = re.compile(args.grep)
		posts = [ p for p in posts if
				re.search(e, p['topic']['title']) or
				re.search(e, p['raw']) ]

	json.dump(posts, sys.stdout, indent=2)

def do_format(args):
	'''Summarize the data in a custom text format'''
	posts = Post.load(args.json)
	for p in posts:
		ln = args.template
		for m in re.finditer('{([^}:]+)([^}]*)}', args.template):
			field = m.group(1)
			fmt = m.group(2)

			try:
				if 'shortdate' == field:
					val = p['created_at'][:10]
				elif '-' in field:
					(field, attr) = field.split('-', 1)
					val = p[field][attr]
				else:
					val = p[field]
			except KeyError:
				continue

			ln = ln.replace(m.group(0), '{{{}}}'.format(fmt).format(val))
		print(ln)

def do_interact(args):
	'''Directly interact with the JSON data'''
	posts = Post.load(args.json)
	post = posts[-1]

	cfg = config.get_config()
	client = pydiscourse.DiscourseClient( cfg['96btool']['server'],
			api_username=cfg['96btool']['username'],
			api_key=config.get_password(cfg, '96btool'),
			timeout=5)

	interact()

def do_merge(args):
	'''Read multiple concatenated JSON files and merge into one'''
	decoder = json.JSONDecoder()

	s = sys.stdin.read()

	posts = []

	while s:
		(p, i) = decoder.raw_decode(s)
		posts += p
		s = s[i:]

	# De-duplicate and sort by id
	posts = [ Post(p) for p in posts ]
	Post.index(posts)
	posts = [ Post.post_db[k] for k in sorted(Post.post_db.keys()) ]

	json.dump(posts, sys.stdout, sort_keys=True, indent=2)

def do_monthly(args):
	'''Generate a monthly activity report'''
	try:
		with open(os.environ['HOME']+'/.96btool-highlight_nicks') as f:
			hlnicks = json.load(f)
	except IOError:
		hlnicks = ()

	digest = {}
	for p in Post.load(args.json):
		if p['topic']['title'] not in digest:
			digest[p['topic']['title']] = p
			p['count'] = 1
		else:
			digest[p['topic']['title']]['count'] += 1

	# Sort alphabetically by subject and re-index by topic
	by_topic = collections.defaultdict(list)
	for s in sorted(digest.keys()):
		topic = digest[s]['topic']['category']
		by_topic[topic].append(digest[s])

	print('''\
<table border=2>
<tr>
<td>Board</td>
<td>Posts</td>
</tr>
''')

	for t in sorted(by_topic.keys()):
		total_posts = 0
		for s in by_topic[t]:
			total_posts += s['count']

		print('<tr>')
		print('<td>{}<br>{} post{}, {} topic{}</td>'.format(
			t, total_posts, 's' if total_posts > 1 else '',
			len(by_topic[t]), 's' if len(by_topic[t]) > 1 else ''))
		print('<td><ul>')
		for s in by_topic[t]:
			if s['topic']['username'] in hlnicks:
				em = 'strong'
			else:
				em = 'em'
			print('<li>{} by <{}>{}</{}> (<a href="{}">{} post{}</a>)</li>'.format(
					s['topic']['title'], em, s['topic']['username'], em, s['topic']['uri'], s['count'], 's' if s['count'] > 1 else ''))
		print('</ul></td></tr>')
	print('</table>')

def do_passwd(args):
	'''Store a password in the keyring'''
	print("WARNING: This is *not* your forum password. It is an API key")
	print("         issued to allow JSON access to discourse.")
	cfg = config.get_config()
	config.set_password(cfg, '96btool')

def do_piechart(args):
	'''Visualise data as a pie chart'''
	count = load_json(args.json)
	try:
		# Assume the incoming JSON is a dictionary created by
		# 96btool count
		chart.piechart(count, args.output, args.title)
	except AttributeError:
		# Hmnn... guess this is just a list of posts then...
		posts = [ Post(p) for p in count ]
		count = collect.accumulate(posts,
				lambda p: p['topic']['category'])
		chart.piechart(count, args.output, args.title)

def do_pull(args):
	'''Update the local cache of the database'''
	cfg = config.get_config()
	client = pydiscourse.DiscourseClient( cfg['96btool']['server'],
			api_username=cfg['96btool']['username'],
			api_key=config.get_password(cfg, '96btool'),
			timeout=5)

	if args.verbose:
		sys.stdout.write('Reading existing post cache .')
		sys.stdout.flush()
	try:
		posts = Post.load(args.db)
		Post.index(posts)

		if args.verbose:
			sys.stdout.write('..')
			sys.stdout.flush()
	except (FileNotFoundError, ValueError):
		if args.verbose:
			sys.stdout.write('.. file not found -')

	if len(Post.post_db) and not args.refresh:
		max_post_id = max([ i for i in Post.post_db.keys() ])
	else:
		max_post_id = 0

	# Grab the latest topics (we can use these to figure out the
	# most recent post_id)
	if args.verbose:
		print(' {} posts'.format(len(Post.post_db)))
		sys.stdout.write('Looking at the latest topics ...')
		sys.stdout.flush()
	latest_post_id = Post.latest(client)

	# Start grabbing the posts
	if args.verbose:
		sys.stdout.write(' ok\nFetching posts from #{} to #{} .'.format(
				max_post_id + 1, latest_post_id))
		sys.stdout.flush()
	try:
		# fetch automatically indexes as it works so we can ignore
		# the return value here...
		Post.fetch(client, max_post_id+1, latest_post_id+1,
				verbose=args.verbose)
		retval = 0

	except BaseException as e:
		if args.verbose:
			sys.stdout.write(' abort (and save progress)\n')
		if args.debug:
			traceback.print_exc()
		else:
			print('ERROR: {} ...'.format(str(e)), file=sys.stderr)
		retval = 1
	finally:
		# Final tidy up (reconstruct posts from the post_db)
		if args.verbose:
			sys.stdout.write(
				' ok\nPerforming final cleanup ...'.format(
					retval))
			sys.stdout.flush()
		posts = [ Post.post_db[k] for k in sorted(Post.post_db.keys()) ]

		os.rename(args.db, args.db + '.bak')
		with open(args.db, 'w') as f:
			json.dump(posts, f, sort_keys=True, indent=2)

		if args.verbose:
			print(' ok')

	if args.pipe:
		json.dump(posts, sys.stdout, indent=2)

	return retval

def do_refresh(args):
	'''Refresh the local database and fix minor integrity errors'''
	cfg = config.get_config()
	client = pydiscourse.DiscourseClient( cfg['96btool']['server'],
			api_username=cfg['96btool']['username'],
			api_key=config.get_password(cfg, '96btool'),
			timeout=5)

	posts = Post.load(args.db)
	Post.index(posts)

	if args.users:
		with open(args.users, 'r') as f:
			users = json.load(f)
		for u in users:
			Post.user_db[u['username']] = u

	# TODO: try to download any missing post ids

	try:
		for p in posts:
			if args.users:
				if p['username'] not in Post.user_db:
					print('No info for user {}'.format(p['username']), file=sys.stderr)
				else:
					p['user'] = Post.user_db[p['username']]
			else:
				if 'user' not in p and p['username']:
					if args.verbose and p['username'] not in Post.user_db:
						print('Refreshing user {}'.format(p['username']), file=sys.stderr)
					p.get_user(client)
			if p.lint():
				del Post.post_db[p['id']]
	except BaseException as e:
		traceback.print_exc()
	finally:
		posts = [ Post.post_db[k] for k in sorted(Post.post_db.keys()) ]

		os.rename(args.db, args.db + '.bak')
		with open(args.db, 'w') as f:
			json.dump(posts, f, sort_keys=True, indent=2)

def do_tag(args):
	'''Tag posts that match certain criteria'''
	posts = Post.load(args.json)

	tag_with = args.tag_with if args.tag_with else 'Marked'

	if args.user:
		users = args.user.split(',')
	else:
		users = []

	if args.usermap:
		(usermap, needle) = args.usermap.split(',', maxsplit=1)
		with open(usermap, 'r') as f:
			usermap = json.load(f)

	def tag(p):
		if args.unique:
			p['tags'] = [ tag_with, ]
		elif tag_with not in p['tags']:
			p['tags'].append(tag_with)

	for p in posts:
		if 'tags' not in p:
			p['tags'] = []

		if p['username'] in users:
			tag(p)

		if args.usermap and p['username'] in usermap and \
				needle in usermap[p['username']]:
			tag(p)

		if args.empty and len(p['tags']) == 0:
			tag(p)

	json.dump(posts, sys.stdout, indent=2)

def do_weekly(args):
	'''Generate a detailed weekly activity report'''
	wrappers = (
		textwrap.TextWrapper(),
		textwrap.TextWrapper(initial_indent=' * ', subsequent_indent='   '),
		textwrap.TextWrapper(initial_indent='   - ', subsequent_indent='     ')
	)

	def wrap(msg, level):
		print('\n'.join(wrappers[level].wrap(msg)))

	posts = Post.load(args.json)

	wrap('96Boards forum activity ({} posts)'.format(len(posts)), level=1)

	summary = collect.accumulate(posts, lambda p: p['topic']['title'])
	for s in sorted(summary.keys()):
		if summary[s] == 1:
			wrap(s, level=2)
		else:
			wrap('{} ({} posts)'.format(s, summary[s]), level=2)

def do_worklog(args):
	summary = collections.defaultdict(int)
	for p in Post.load(args.json):
		summary[p['topic']['title']] += 1

	items = []
	for s in sorted(summary.keys()):
		if summary[s] == 1:
			items.append(' * {}'.format(s))
		else:
			items.append(' * {} ({} posts)'.format(s, summary[s]))

	if not args.time_spent:
		print("No time spent estimate. Please use the following as a memory jogger.\n")
		for i in items:
			print(textwrap.fill(i, subsequent_indent='   '))
		return

	jira = config.connect_to_jira()
	if not args.issue:
		args.issue = config.get_config()['96btool']['jiralink']
	if args.date:
		args.date = date.smart_parse(args.date)
	jira.add_worklog(args.issue, timeSpent=args.time_spent, started=args.date, comment='\n'.join(items))

def main(argv):
	defaultdb=os.path.dirname(os.path.realpath(sys.argv[0])) + '/../96btool.db'

	parser = argparse.ArgumentParser()
	subparsers = parser.add_subparsers(dest='sub-command')
	subparsers.required = True	# Can't be set using named arguments (yet)

	def new_parser(f, no_json_arg=False):
		assert(f.__name__.startswith('do_'))
		name = f.__name__[3:]
		helptext = f.__doc__
		s = subparsers.add_parser(name, help=helptext)
		s.set_defaults(func=f)
		if not no_json_arg:
			s.add_argument('json', nargs='?',
					help='Read data from this file')

		return s

	s = new_parser(do_chart)
	s.add_argument('--by-tag', action='store_true',
			help='Use tags to collate posts')
	s.add_argument("--output", default="96btool.png")
	s.add_argument("--title",
			help='Title for the graph')

	s = new_parser(do_count)
	s.add_argument('--csv', action='store_true',
		       help="Show the count data as CSV")
	s.add_argument('--simplify', action='store_true',
			help="Combine values less than 1 percent")
	s.add_argument('--by-category', action='store_true',
			help="Count posts in each category")
	s.add_argument('--by-user', action='store_true',
			help="Count posts by each user")
	s.add_argument('--rank', action='store_true',
			help="Sort the data into reverse numeric order")
	s.add_argument('--text', action='store_true',
			help="Show results in plain text")

	s = new_parser(do_dump, no_json_arg=True)
	s.add_argument('--db', default=defaultdb,
		       help="File to update")

	s = new_parser(do_fetch, no_json_arg=True)
	s.add_argument("--query", default="@danielt",
		        help="Nickname to fetch replies from");
	s.add_argument("--since", default="2012-01-01",
			help="When to gather information from")

	s = new_parser(do_filter)
	s.add_argument("--category",
			help="Filter by forum category")
	s.add_argument("--first-post", action='store_true',
			help="Discard replies; keep only the first post in each topic")
	s.add_argument("--grep",
			help="Search for a string within a post")
	s.add_argument("--since", default="2012-01-01",
			help="When to gather information from")
	s.add_argument('--tag',
			help='Filter by tag (exact match needed)')
	s.add_argument("--until", default="tomorrow",
			help="When to stop gathering .information")
	s.add_argument("--user", help="Select only posts by this user")

	s = new_parser(do_format)
	s.add_argument("--template",
			default="{id}: {topic-title} ({username})")

	s = new_parser(do_interact)
	s.add_argument("json", nargs='?', default=defaultdb)

	s = new_parser(do_merge, no_json_arg=True)

	s = new_parser(do_monthly)

	s = new_parser(do_passwd, no_json_arg=True)

	s = new_parser(do_piechart)
	s.add_argument("--title", default=None)
	s.add_argument("--output", default="96btool.png")

	s = new_parser(do_pull, no_json_arg=True)
	s.add_argument('--debug', action='store_true',
		       help="Extra diagnostics")
	s.add_argument('--db', default=defaultdb,
		       help="File to update")
	s.add_argument('--pipe', action='store_true',
		       help="Duplicate output on stdout")
	s.add_argument('--refresh', action='store_true',
		       help="Try to fetch posts missing due to previous errors")
	s.add_argument('--verbose', action='store_true',
		       help="Show internal workings")

	s = new_parser(do_refresh, no_json_arg=True)
	s.add_argument('--db', default=defaultdb,
		       help="File to update")
	s.add_argument('--verbose', action='store_true',
		       help="Show internal workings")
	s.add_argument('--users', help='Use a local copy of the user list')

	s = subparsers.add_parser('summary', help=do_format.__doc__)
	s.set_defaults(func=do_format,
		       template="{shortdate}: {topic-title} ({username})")
	s.add_argument('json', nargs='?',
			help='Read data from this file')

	s = new_parser(do_tag)
	s.add_argument('--empty', action='store_true',
			help='Tag posts with no tags')
	s.add_argument('--tag-with',
			help="Tag to apply, defaults to 'Marked'")
	s.add_argument('--unique', action='store_true',
			help='Remove existing tags before tagging')
	s.add_argument('--user', help='Tag only posts by this user')
	s.add_argument('--usermap', help='Tag post using a lookup table')
	s.add_argument('json', nargs='?',
			help='Read data from this file')

	s = new_parser(do_weekly)
	s.add_argument('json', nargs='?',
			help='Read data from this file')

	s = subparsers.add_parser('worklog')
	s.add_argument("--issue")
	s.add_argument("--time-spent")
	s.add_argument("--date")
	s.add_argument('json', nargs='?',
			help='Read data from this file')
	s.set_defaults(func=do_worklog)

	args = parser.parse_args(argv[1:])
	return args.func(args)

if __name__ == "__main__":
	try:
		sys.exit(main(sys.argv))
	except KeyboardInterrupt:
		sys.exit(1)
	sys.exit(127)