#!/usr/bin/python3

import subprocess, sys
from datetime import date

TEMPLATE = '''%% %s(1) git-toolbelt %s
%% Vincent Driessen
%% %s

# NAME
%s

# DESCRIPTION
%s

# GIT TOOLBELT
Part of the **git-toolbelt**(1) suite.
'''

man_pages = []
man_files = {}
text = ''
version = sys.argv[1]

print('Generating...')

with open('README.md', 'r') as f:
	for line in f:
		if line.startswith('# git'):
			man_pages = ['git-toolbelt']
		elif line.startswith('### git'):
			man_pages = line.split('/')
			man_pages = map(lambda x: x.strip('# \n').replace('git ', 'git-'), man_pages)
		else:
			if man_pages:
				for mpage, mfile in man_files.items():
					print('+ %s' % mpage)
					t = TEMPLATE % (mpage.upper(), version, date.today().isoformat(), "%s (%s)" % (mpage, mpage.replace("git-", "git ")), text)
					p = subprocess.Popen(['pandoc', '-s', '-t', 'man', '-f', 'markdown', '-o', 'mans/%s.1' % mpage], stdin=subprocess.PIPE)
					p.communicate(input=t.encode('utf-8'))
				text = ''
				man_files = {}
				for mpage in man_pages:
					man_files[mpage] = 1
				man_pages = []
			text += line

print('done.')
