#!/usr/bin/env python
# this script uses dulwich
# - https://pypi.python.org/pypi/dulwich
# - https://www.dulwich.io/
# - https://github.com/jelmer/dulwich
from dulwich.repo import Repo
from dulwich.objects import Blob, Tree, Commit, parse_timezone
from subprocess import check_call
import platform
from os import listdir
from os.path import join, isdir
from time import time
import shutil

shutil.rmtree('target/doc')
check_call(('cargo', 'doc', '--no-deps'))
if platform.system() == 'FreeBSD':
	# XXX more hard-coded things
	check_call(('cargo', 'doc', '--no-deps', '-p', 'cam'))

repo = Repo('.')

def dir_to_tree(repo, d):
	tree = Tree()
	for i in listdir(d):
		file = join(d, i)
		if isdir(file):
			child = dir_to_tree(repo, file)
			tree.add(i.encode(), 0o040000, child.id)
		else:
			if i.endswith('.woff'): continue
			# FIXME might eat your RAM, your dog, and your children
			# XXX Blob.from_file is not what you think it is
			child = Blob.from_string(open(file, 'rb').read())
			tree.add(i.encode(), 0o100644, child.id)
		repo.object_store.add_object(child)
	return tree

# update subtree for specific platform

subtree = dir_to_tree(repo, 'target/doc')
repo.object_store.add_object(subtree)

commit = repo.get_object(repo.refs[b'refs/heads/gh-pages'])
tree = repo.get_object(commit.tree)
tree[platform.system().lower().encode()] = (0o040000, subtree.id)
repo.object_store.add_object(tree)

# update index page
# TODO? non-hard-coded page

index = Blob.from_string(b'''
<meta charset="utf-8">
Documentation for all platforms should generally be the same, and you can click on any of the following links unless you're dealing with bindings and other lower level things.
<ul>
<li> <a href="./linux/hdd">Linux</a>
<li> <a href="./freebsd/hdd">FreeBSD</a>
</ul>
''')
repo.object_store.add_object(index)

tree.add(b'index.html', 0o100644, index.id)
repo.object_store.add_object(tree)

# commit updated tree

commit = Commit()
commit.tree = tree.id
commit.author = commit.committer = b'gh-pages generator script <whatever@localhost>'
commit.commit_time = commit.author_time = int(time())
commit.commit_timezone = commit.author_timezone = parse_timezone(b'+0000')[0]
commit.encoding = b'UTF-8'
commit.message = "'cargo doc --no-deps' for 'hdd' on {system}, commit {commit}".format(
	system = platform.system().lower(),
	commit = repo.head().decode(),
).encode()
commit.parents = [repo.refs[b'refs/heads/gh-pages']]

repo.object_store.add_object(commit)
repo.refs[b'refs/heads/gh-pages'] = commit.id

print('''
Now you can do:
	git push github gh-pages
''')
