/*
 * repostead --- repository homesteading tool
 *
 * Copyright (c) 2026 Amin Bandali <amin@shemshak.org>
 *
 * repostead is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * repostead is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with repostead.  If not, see <https://www.gnu.org/licenses/>.
 */

#define _XOPEN_SOURCE 700
#include <assert.h>
#include <errno.h>
#include <inttypes.h>
#include <limits.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>

#include <git2.h>

#ifdef HAVE_LOWDOWN
#include <sys/queue.h>
#include <lowdown.h>
#endif

#define RS_NAME "repostead"
#define RS_VERSION "0.1.0"

#define RS_PATH_MAX 4096
/* UINT64_MAX (20 digits) + space + 3-char unit + NULL */
#define RS_FILE_INFO_SIZE_STRLEN 25
#define RS_FILE_INFO_MODE_STRLEN 11 /* 10 chars + NULL */

#define RS_TREE_ROOT "tree"
#define RS_RAW_ROOT "raw"
#define RS_LOG_ROOT "log"

#if defined(__has_c_attribute)
#if __has_c_attribute(nodiscard) \
	&& defined(__STDC_VERSION__) && __STDC_VERSION__ >= 202311L
#define NODISCARD [[nodiscard]]
#define NORETURN [[noreturn]]
#endif
#endif
#if !defined(NODISCARD)
#if defined(__GNUC__)
#define NODISCARD __attribute__((warn_unused_result))
#else
#define NODISCARD
#endif
#endif
#if !defined(NORETURN)
#if defined(__GNUC__)
#define NORETURN __attribute__((noreturn))
#else
#define NORETURN
#endif
#endif

struct repostead_config {
	const char *clone_url;
	const char *repo_path;
	const char *out_path;
	const char *repo_name;
	const char *repo_git_dir;
	const char *repo_desc;
	git_repository *repo;
};

struct repostead_branch {
	const char *name;
	char dir[RS_PATH_MAX];
	git_tree *tree;
};

struct repostead_file_info {
	const char *name;
	const char *dir;
	char size[RS_FILE_INFO_SIZE_STRLEN];
	char mode[RS_FILE_INFO_MODE_STRLEN];
};

static const char *const readme_files[] = {
	"README", "README.md"
};

static const char *const html_ent[UCHAR_MAX + 1] = {
	['<'] = "&lt;",
	['>'] = "&gt;",
	['&'] = "&amp;",
	['"'] = "&quot;",
	['\''] = "&#39;",
	['\0'] = "&#9216;",
	['\f'] = "&#9228;",
	['\v'] = "&#9238;",
};


static void
vwarn(const char *fmt, va_list ap)
{
	fputs(RS_NAME ": ", stderr);
	vfprintf(stderr, fmt, ap);
	fputc('\n', stderr);
}

static void
warn(const char *fmt, ...)
{
	va_list ap;
	va_start(ap, fmt);
	vwarn(fmt, ap);
	va_end(ap);
}

NORETURN
static void
die(const char *fmt, ...)
{
	va_list ap;
	va_start(ap, fmt);
	vwarn(fmt, ap);
	va_end(ap);
	exit(EXIT_FAILURE);
}

NORETURN
static void
gitdie(const char *msg)
{
	const git_error *e = git_error_last();
	die("%s: %s", msg, e && e->message ? e->message : "unknown error");
}

static void
xmkdir(const char *path)
{
	struct stat st;
	int err = 0;

	if (mkdir(path, 0755) == 0) {
		return;
	}
	err = errno;
	if (err == EEXIST) {
		if (stat(path, &st) == 0 && S_ISDIR(st.st_mode)) {
			return;
		}
		die("failed to create %s: exists and is not a directory", path);
	}
	die("failed to create %s: %s", path, strerror(err));
}

static void
html_escn(FILE *f, const char *s, size_t len)
{
	const char *run = s, *end = s + len;

	/* write each run of safe characters in one go */
	for (; s < end; s++) {
		const char *ent = html_ent[(unsigned char)*s];
		if (ent) {
			fwrite(run, 1, (size_t)(s - run), f);
			fputs(ent, f);
			run = s + 1;
		}
	}
	fwrite(run, 1, (size_t)(end - run), f);
}

static void
html_esc(FILE *f, const char *s)
{
	html_escn(f, s, strlen(s));
}

static bool
rfc3986_unreserved(int c)
{
	return c > 0 && c < 128 && strchr(
		"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
		"abcdefghijklmnopqrstuvwxyz"
		"0123456789"
		"-._~", c) != NULL;
}

static void
url_encn(FILE *f, const char *s, size_t len)
{
	for (; len > 0; s++, len--) {
		unsigned char c = (unsigned char)*s;
		if (rfc3986_unreserved(c) || c == '/') {
			putc(c, f);
		} else {
			fprintf(f, "%%%02X", c);
		}
	}
}

static void
url_enc(FILE *f, const char *s)
{
	url_encn(f, s, strlen(s));
}

static void
write_header(FILE *f, const struct repostead_config *conf, const char *title,
	bool is_root)
{
	fputs(
		"<!DOCTYPE html><html lang=\"en\"><head>"
		"<meta charset=\"utf-8\" />"
		"<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />"
		"<meta name=\"color-scheme\" content=\"light dark\" />"
		"<title>", f);
	html_esc(f, title);
	fputs(
		"</title>"
		"<style>"
		"body{font-family:sans-serif}"
		"h1{font-size:1.25em}h2{font-size:1.125em;margin-bottom:0.5em}"
		"h2 small{font-weight:normal}"
		".desc{margin-bottom:0.6em}.clone{margin-top:0.6em}"
		"table{border-collapse:collapse}"
		"th{padding:0.3em 0.6em}td{padding:0.2em 0.6em}"
		"tr:hover,tr:has(a:focus){background-color:#f2f2f2}"
		".tree-list{font-family:monospace}"
		".tree-list a:hover{text-decoration:none}"
		".tree-list .s{text-align:right}"
		".dir .n, .sub .n{font-weight:bold}"
		"pre .ln{display:table-cell;color:grey;text-decoration:none;"
		"user-select:none;border-right:1px solid;padding:0 0.75em 0 0.25em}"
		"pre .ln:hover{color:black}"
		"pre code{display:table-row}"
		"pre code:after{content:\"\";display:table-cell;width:100%}"
		"pre code:target{background-color:#fffbdd}"
		"@media(prefers-color-scheme:dark){"
		"tr:hover,tr:has(a:focus){background-color:#25242b}"
		"pre .ln:hover{color:white}"
		"pre code:target{background-color:#302d17}"
		"}"
		"</style>"
		"</head><body>"
		"<h1>", f);
	html_esc(f, conf->repo_name);
	fputs(
		"</h1>"
		"<p class=\"desc\">", f);
	html_esc(f, conf->repo_desc);
	fputs("</p>", f);
	if (strcmp(conf->clone_url, "") != 0) {
		fprintf(f, "<p class=\"clone\"><code>git clone %s</code></p>",
			conf->clone_url);
	}
	if (!is_root) {
		fputs("<hr />", f);
	}
}

static void
write_footer(FILE *f)
{
	fputs("</body></html>", f);
}

NODISCARD
static bool
path_join(char *dest, size_t dsize, const char *a, const char *b)
{
	const char *sep = NULL;
	int n = 0;

	assert(a && b);
	sep = (*a && a[strlen(a) - 1] != '/' && *b != '/') ? "/" : "";
	n = snprintf(dest, dsize, "%s%s%s", a, sep, b);
	return n >= 0 && (size_t)n < dsize;
}

static void
xpath_join(char *dest, size_t dsize, const char *a, const char *b)
{
	if(!path_join(dest, dsize, a, b)) {
		die("path too long: %s/%s", a, b);
	}
}

NODISCARD
static bool
path_ext(char *dest, size_t dsize, const char *path, const char *ext)
{
	const char *dot = NULL;
	int n = 0;

	assert(path && ext && *ext);
	dot = (*ext == '.') ? "" : ".";
	n = snprintf(dest, dsize, "%s%s%s", path, dot, ext);
	return n >= 0 && (size_t)n < dsize;
}

static size_t
path_basename(const char *path, size_t *end)
{
	size_t beg_ = 0, end_ = *end;

	while (end_ > 0 && path[end_ - 1] == '/') {
		end_--;
	}
	beg_ = end_;
	while (beg_ > 0 && path[beg_ - 1] != '/') {
		beg_--;
	}
	*end = end_;
	return beg_;
}

static size_t
path_dirname(const char *path, size_t *end)
{
	size_t e = *end, end_ = path_basename(path, &e);

	while (end_ > 0 && path[end_ - 1] == '/') {
		end_--;
	}
	if (end_ == 0 && *end > 0 && path[0] == '/') {
		end_ = 1;
	}
	*end = end_;
	return 0;
}

static int
mkdirs_(char *path, mode_t mode)
{
	struct stat st;
	size_t len, end;
	char saved;
	int ret;

	if (mkdir(path, mode) == 0) {
		return 0;
	}
	if (errno == ENOENT) {
		len = end = strlen(path);
		(void)path_dirname(path, &end);
		if (end == 0 || end >= len) {
			return -1;
		}
		saved = path[end];
		path[end] = 0;
		ret = mkdirs_(path, mode | S_IWUSR | S_IXUSR);
		path[end] = saved;
		if (ret != 0) {
			return -1;
		}
		if (mkdir(path, mode) == 0) {
			return 0;
		}
	}
	if (errno == EEXIST) {
		if (stat(path, &st) == 0 && S_ISDIR(st.st_mode)) {
			return 0;
		}
		errno = ENOTDIR;
	}
	return -1;
}

static int
mkdirs(const char *path, mode_t mode)
{
	char p[RS_PATH_MAX] = "";
	size_t len = strlen(path);

	if (len == 0) {
		errno = ENOENT;
		return -1;
	}
	else if (len >= sizeof(p)) {
		errno = ENAMETOOLONG;
		return -1;
	}
	memcpy(p, path, len + 1);
	return mkdirs_(p, mode);
}

static void
xmkdirs(const char *path)
{
	if (mkdirs(path, 0755) < 0) {
		die("failed to mkdirs %s: %s", path, strerror(errno));
	}
}

static size_t
path_depth(const char *path)
{
	size_t beg, end = strlen(path), n = 0;

	for (;;) {
		beg = path_basename(path, &end);
		if (beg == end) {
			break;
		}
		n++;
		end = beg;
	}
	return n;
}

static void
path_ups(FILE *f, size_t ups)
{
	size_t i;

	if (ups == 0) {
		fputc('.', f);
		return;
	}
	fputs("..", f);
	for (i = 1; i < ups; i++) {
		fputs("/..", f);
	}
}

static void
path_crumb(FILE *f, const char *s, size_t len, bool link, size_t ups)
{
	if (link) {
		fputs("<a href=\"", f);
		path_ups(f, ups);
		fputs("\">", f);
	}
	html_escn(f, s, len);
	if (link) {
		fputs("</a>", f);
	}
}

static void
path_breadcrumb(FILE *f, const char *branch, const char *root,
	const char *path, bool is_file)
{
	size_t n = path_depth(path);
	size_t ups = (is_file && n > 0) ? n - 1 : n;
	size_t beg, end = 0, i;

	path_crumb(f, branch, strlen(branch), true, ups + 1);
	fputc('/', f);
	path_crumb(f, root, strlen(root), n > 0, ups);

	for (i = 0; i < n; i++) {
		bool link = i + 1 < n;

		beg = end + strspn(path + end, "/");
		end = beg + strcspn(path + beg, "/");
		fputc('/', f);
		path_crumb(f, path + beg, end - beg, link,
			link ? ups - (i + 1) : 0);
	}
}

static void
path_across_roots(FILE *f, const char *from, const char *to,
	const char *dir, const char *name)
{
	if (strcmp(from, to) != 0) {
		path_ups(f, path_depth(dir) + 1);
		fputc('/', f);
		url_enc(f, to);
		fputc('/', f);
		if (*dir) {
			url_enc(f, dir);
			fputc('/', f);
		}
	}
	url_enc(f, name);
}

static void
branch_path(char *dest, size_t dsize,
	const struct repostead_config *conf,
	const struct repostead_branch *br, const char *root, const char *path)
{
	assert(root && *root && path);
	if (*path) {
		char root_dir[RS_PATH_MAX] = "";
		xpath_join(root_dir, sizeof(root_dir), br->dir, root);
		xpath_join(dest, dsize, root_dir, path);
	} else {
		xpath_join(dest, dsize, br->dir, root);
	}
}

/* from curl's curlx_strcopy */
static void
str_copy(char *dest, size_t dsize, const char *src, size_t slen)
{
	assert(slen < dsize);
	if (slen < dsize) {
		memcpy(dest, src, slen);
		dest[slen] = 0;
	} else if (dsize) {
		dest[0] = 0;
	}
}

static void
repo_name_from_path(char *dest, size_t dsize, const char *path)
{
	size_t end = strlen(path);
	size_t beg = path_basename(path, &end);

	if (end - beg == 4 && memcmp(path + beg, ".git", 4) == 0) {
		/* repo/.git -> repo */
		end = beg;
		beg = path_basename(path, &end);
	} else if (end - beg > 4 && memcmp(path + end - 4, ".git", 4) == 0) {
		/* repo.git -> repo */
		end -= 4;
	}

	if (end == beg) {
		die("could not make a repo name from \"%s\"", path);
	}
	if (end - beg >= dsize) {
		die("repo name too long");
	}
	str_copy(dest, dsize, path + beg, end - beg);
}

NODISCARD
static bool
format_bytes(char *dest, size_t dsize, uint64_t bytes)
{
	static const char *const units[] = {
		"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"
	};
	const int max_unit = ((int)(sizeof(units) / sizeof(units[0]))) - 1;
	double size;
	int i, n;

	assert(dest);
	size = (double)bytes;
	i = 0;

	while (size >= 1024.0 && i < max_unit) {
		size /= 1024.0;
		i++;
	}

	/* if we round up to 1024.0, move up to the next unit */
	if (i > 0 && i < max_unit && size >= 1023.95) {
		size /= 1024.0;
		i++;
	}

	if (i == 0) {
		n = snprintf(dest, dsize, "%" PRIu64 " %s", bytes, units[0]);
	} else {
		n = snprintf(dest, dsize, "%.1f %s", size, units[i]);
	}

	return n >= 0 && ((size_t)n) < dsize;
}

static char *
git_filemode_str(char dest[RS_FILE_INFO_MODE_STRLEN], git_filemode_t mode)
{
	static const char rwx[] = "rwxrwxrwx";
	size_t i;

	memset(dest, '-', RS_FILE_INFO_MODE_STRLEN - 1);
	dest[RS_FILE_INFO_MODE_STRLEN - 1] = 0;

	switch (mode & 0170000) {
	case 0100000: /* blob */
		for (i = 0; i < sizeof(rwx) - 1; i++) {
			if (mode & (0400 >> i)) {
				dest[i + 1] = rwx[i];
			}
		}
		break;
	case GIT_FILEMODE_TREE:
		dest[0] = 'd';
		break;
	case GIT_FILEMODE_LINK:
		dest[0] = 'l';
		break;
	case GIT_FILEMODE_COMMIT:
		dest[0] = 'm';
		break;
	default:
		dest[0] = '?';
		break;
	}

	return dest;
}

static bool
tree_name_okn(const char *name, size_t len)
{
	return len > 0
		&& !(len == 1 && name[0] == '.')
		&& !(len == 2 && name[0] == '.' && name[1] == '.')
		&& memchr(name, '/', len) == NULL;
}

static bool
tree_name_ok(const char *name)
{
	return tree_name_okn(name, strlen(name));
}

static bool
branch_name_ok(const char *name)
{
	for (;;) {
		size_t len = strcspn(name, "/");

		if (!tree_name_okn(name, len)) {
			return false;
		}
		if (name[len] == 0) {
			return true;
		}
		name += len + 1;
	}
}

static FILE *
page_begin(const struct repostead_config *conf,
	const char *path, const char *title, bool is_root)
{
	FILE *f = fopen(path, "w");
	if (!f) {
		die("failed to open %s for writing: %s", path, strerror(errno));
	}
	write_header(f, conf, title, is_root);
	return f;
}

static void
page_end(FILE *f, const char *path)
{
	int err = 0;
	write_footer(f);
	err = ferror(f);
	if (fclose(f) == EOF || err) {
		die("error writing %s: %s", path, strerror(errno));
	}
}

static size_t
str_linecount(const char *s, size_t len)
{
	const char *end = s + len, *p = s;
	size_t n = 0;

	while (p < end && (p = memchr(p, '\n', (size_t)(end - p))) != NULL) {
		n++;
		p++;
	}
	if (len > 0 && s[len - 1] != '\n') {
		n++;
	}
	return n;
}

static void
print_listing(FILE *f, const char *s, size_t len)
{
	const char *end = s + len;
	size_t total = str_linecount(s, len), l = 1, t = 0;
	int width = 1;

	for (t = total; t >= 10; t /= 10) {
		width++;
	}

	fputs("<pre>", f);
	while (s < end) {
		const char *nl = memchr(s, '\n', (size_t)(end - s));
		const char *eol = nl ? nl : end;

		fprintf(f, "<code id=\"L%zu\">", l);
		fprintf(f, "<a href=\"#L%zu\" class=\"ln\">%*zu</a>&nbsp;",
			l, width, l);
		html_escn(f, s, (size_t)(eol - s));
		fputs("</code>", f);
		if (nl) {
			putc('\n', f);
			s = nl + 1;
		} else {
			s = end;
		}
		l++;
	}
	fputs("</pre>", f);
}


static void
process_file(struct repostead_file_info *fi,
	const struct repostead_config *conf,
	const struct repostead_branch *br, const git_blob *blob)
{
	char html_dir[RS_PATH_MAX] = "";
	char raw_dir[RS_PATH_MAX] = "";
	char file_path[RS_PATH_MAX] = "";
	char file_html_path[RS_PATH_MAX] = "";
	char file_html_base[RS_PATH_MAX] = "";
	char file_rel_path[RS_PATH_MAX] = "";
	FILE *file = NULL;
	FILE *file_html = NULL;
	const void *data = NULL;
	git_object_size_t size = 0;

	branch_path(html_dir, sizeof(html_dir), conf,
		br, RS_TREE_ROOT, fi->dir);
	branch_path(raw_dir, sizeof(raw_dir), conf,
		br, RS_RAW_ROOT, fi->dir);

	xpath_join(file_path, sizeof(file_path), raw_dir, fi->name);
	xpath_join(file_html_base, sizeof(file_html_base), html_dir, fi->name);
	if (!path_ext(file_html_path, sizeof(file_html_path),
			file_html_base, "html")) {
		die("file path too long %s.html", file_html_base);
	}
	xpath_join(file_rel_path, sizeof(file_rel_path), fi->dir, fi->name);

	data = git_blob_rawcontent(blob);
	size = git_blob_rawsize(blob);

	if (size > SIZE_MAX) {
		die("blob too large");
	}

	file = fopen(file_path, "wb");
	if (!file) {
		die("failed to open file %s for writing: %s",
			file_path, strerror(errno));
	}

	if (size > 0 && fwrite(data, 1, (size_t)size, file) != (size_t)size) {
		die("error writing %s", file_path);
	} else if (fclose(file) == EOF) {
		die("error writing %s: %s", file_path, strerror(errno));
	}

	file_html = page_begin(conf, file_html_path, fi->name, false);

	if (!format_bytes(fi->size, sizeof(fi->size), size)) {
		die("file size string too long");
	}

	fputs("<h2>", file_html);
	path_breadcrumb(file_html, br->name, RS_TREE_ROOT, file_rel_path, true);
	fprintf(file_html, " <small>(<span class=\"m\">%s</span>, ", fi->mode);
	fprintf(file_html, "<span class=\"s\">%s</span>, ", fi->size);
	fputs("<a class=\"raw\" href=\"", file_html);
	path_across_roots(file_html, RS_TREE_ROOT, RS_RAW_ROOT,
		fi->dir, fi->name);
	fputs("\">raw</a>)</small></h2>", file_html);

	if (git_blob_is_binary(blob)) {
		fputs("<p>binary file</p>", file_html);
	} else {
		print_listing(file_html, data, (size_t)size);
	}

	page_end(file_html, file_html_path);
}

static void
tree_readme(FILE *f, const struct repostead_config *conf, const git_tree *tree)
{
	size_t i = 0;
	const git_tree_entry *e = NULL;

	for (i = 0; i < sizeof(readme_files) / sizeof(readme_files[0]); i++) {
		e = git_tree_entry_byname(tree, readme_files[i]);
		if (e && git_tree_entry_type(e) == GIT_OBJECT_BLOB) {
			const git_oid *oid = git_tree_entry_id(e);
			git_blob *blob = NULL;
			const void *data = NULL;
			git_object_size_t size = 0;
#ifdef HAVE_LOWDOWN
			size_t fnlen = strlen(readme_files[i]);
			bool is_md = (fnlen >= 3
				&& strcmp(readme_files[i] + fnlen - 3, ".md") == 0);
			struct lowdown_buf *out;
			struct lowdown_doc *doc;
			struct lowdown_node *n;
			struct lowdown_opts opts;
			char *ovr[] = { "shiftheadinglevelby: 1\n" };
			void *rndr;
#endif

			if (git_blob_lookup(&blob, conf->repo, oid) != 0) {
				gitdie("git_blob_lookup");
			}
			data = git_blob_rawcontent(blob);
			size = git_blob_rawsize(blob);
			if (size > SIZE_MAX) {
				die("blob too large");
			}
			fputs("<h2 id=\"readme\">", f);
			html_esc(f, readme_files[i]);
			fputs("</h2>", f);
#ifdef HAVE_LOWDOWN
			if (is_md) {
				memset(&opts, 0, sizeof(opts));
				opts.type = LOWDOWN_HTML;
				opts.maxdepth = 128;
				opts.metaovr = ovr;
				opts.metaovrsz = 1;
				if ((doc = lowdown_doc_new(&opts)) == NULL) {
					die("lowdown_doc_new");
				}
				if ((n = lowdown_doc_parse(doc, NULL, data,
						(size_t)size, NULL)) == NULL) {
					die("lowdown_doc_parse");
				}
				if ((out = lowdown_buf_new(256)) == NULL) {
					die("lowdown_buf_new");
				}
				if ((rndr = lowdown_html_new(NULL)) == NULL) {
					die("lowdown_html_new");
				}
				if (!lowdown_html_rndr(out, rndr, n)) {
					die("lowdown_html_rndr");
				}
				fwrite(out->data, 1, out->size, f);
				lowdown_html_free(rndr);
				lowdown_buf_free(out);
				lowdown_node_free(n);
				lowdown_doc_free(doc);
			} else {
#endif
			print_listing(f, data, (size_t)size);
#ifdef HAVE_LOWDOWN
			}
#endif
			git_blob_free(blob);
		}
	}
}

static void
process_tree(const struct repostead_config *conf,
	const struct repostead_branch *br,
	const git_tree *tree, const char *name, const char *path)
{
	char tree_path[RS_PATH_MAX] = "";
	char raw_path[RS_PATH_MAX] = "";
	const char *index_file_name = "index.html";
	char index_file_path[RS_PATH_MAX] = "";
	FILE *index_file = NULL;
	size_t i = 0, count = git_tree_entrycount(tree);

	branch_path(tree_path, sizeof(tree_path), conf, br, RS_TREE_ROOT, path);
	xmkdir(tree_path);
	branch_path(raw_path, sizeof(raw_path), conf, br, RS_RAW_ROOT, path);
	xmkdir(raw_path);

	xpath_join(index_file_path, sizeof(index_file_path),
		tree_path, index_file_name);
	index_file = page_begin(conf, index_file_path, name, false);

	fputs("<h2>", index_file);
	path_breadcrumb(index_file, br->name, RS_TREE_ROOT, path, false);
	fputs("</h2>", index_file);

	/* directories and submodules */
	fputs("<table class=\"tree-list\">", index_file);
	for (i = 0; i < count; i++) {
		const git_tree_entry *e = git_tree_entry_byindex(tree, i);
		if (git_tree_entry_type(e) == GIT_OBJECT_TREE) {
			const git_oid *oid = git_tree_entry_id(e);
			char mode[RS_FILE_INFO_MODE_STRLEN] = "";
			git_filemode_str(mode, git_tree_entry_filemode_raw(e));
			const char *child_name = git_tree_entry_name(e);
			char child_path[RS_PATH_MAX];
			git_tree *child = NULL;

			if (!tree_name_ok(child_name)) {
				die("child tree name unsafe");
			}

			xpath_join(child_path, sizeof(child_path),
				path, child_name);
			fprintf(index_file,
				"<tr class=\"dir\">"
				"<td class=\"m\">%s</td>",
				mode);
			fputs("<td class=\"n\"><a href=\"", index_file);
			url_enc(index_file, child_name);
			fputs("/\">", index_file);
			html_esc(index_file, child_name);
			fputs("/</a></td><td></td></tr>", index_file);
			if (git_tree_lookup(&child, conf->repo, oid) != 0) {
				gitdie("git_tree_lookup");
			}
			process_tree(conf, br, child, child_name, child_path);
			git_tree_free(child);
		}
		else if (git_tree_entry_filemode(e) == GIT_FILEMODE_COMMIT) {
			const git_oid *oid = git_tree_entry_id(e);
			char mode[RS_FILE_INFO_MODE_STRLEN] = "";
			git_filemode_str(mode, git_tree_entry_filemode_raw(e));
			const char *oid_str = git_oid_tostr_s(oid);
			fprintf(index_file,
				"<tr class=\"sub\">"
				"<td class=\"m\">%s</td>",
				mode);
			fputs("<td class=\"n\">", index_file);
			html_esc(index_file, git_tree_entry_name(e));
			fprintf(index_file,
				" @ %s</td>"
				"<td></td></tr>",
				oid_str);
		}
	}
	/* everything else */
	for (i = 0; i < count; i++) {
		const git_tree_entry *e = git_tree_entry_byindex(tree, i);
		const git_oid *oid = git_tree_entry_id(e);
		if (!(git_tree_entry_type(e) == GIT_OBJECT_TREE
				|| git_tree_entry_filemode(e) == GIT_FILEMODE_COMMIT)) {
			git_blob *blob = NULL;
			struct repostead_file_info fi;

			if (git_blob_lookup(&blob, conf->repo, oid) != 0) {
				gitdie("git_blob_lookup");
			}

			memset(&fi, 0, sizeof(fi));
			fi.name = git_tree_entry_name(e);
			fi.dir = path;

			if (!tree_name_ok(fi.name)) {
				die("child tree name unsafe");
			}

			git_filemode_str(fi.mode, git_tree_entry_filemode_raw(e));
			process_file(&fi, conf, br, blob);
			fprintf(index_file,
				"<tr class=\"file\">"
				"<td class=\"m\">%s</td>",
				fi.mode);
			fputs("<td class=\"n\"><a href=\"", index_file);
			url_enc(index_file, fi.name);
			fputs(".html\">", index_file);
			html_esc(index_file, fi.name);
			fprintf(index_file,
				"</a></td>"
				"<td class=\"s\">%s</td></tr>",
				fi.size);
			git_blob_free(blob);
		}
	}
	fputs("</table>", index_file);

	tree_readme(index_file, conf, tree);

	page_end(index_file, index_file_path);
}

static int
print_diff_line(const git_diff_delta *delta,
	const git_diff_hunk *hunk,
	const git_diff_line *line,
	void *f) /* FILE *f */
{
	if (line->origin == GIT_DIFF_LINE_CONTEXT
			|| line->origin == GIT_DIFF_LINE_ADDITION
			|| line->origin == GIT_DIFF_LINE_DELETION) {
		fprintf((FILE *)f, "%c", line->origin);
	}
	html_escn((FILE *)f, line->content, line->content_len);
	return 0;
}

static void
process_commit(const struct repostead_config *conf,
	const struct repostead_branch *br, git_commit *commit)
{
	char file_base_path[RS_PATH_MAX] = "";
	char file_path[RS_PATH_MAX] = "";
	FILE *file = NULL;
	git_commit *parent = NULL;
	git_tree *parent_tree = NULL;
	git_tree *tree = NULL;
	git_diff *diff = NULL;
	const git_oid *oid = NULL;
	const git_oid *parent_oid = NULL;
	const char *oid_str;
	const char *parent_oid_str;

	if (git_commit_parentcount(commit) > 0) {
		if (git_commit_parent(&parent, commit, 0) < 0) {
			gitdie("git_commit_parent");
		}
		if (git_commit_tree(&parent_tree, parent) < 0) {
			gitdie("git_commit_tree");
		}
		parent_oid = git_commit_id(parent);
		if (!parent_oid) {
			gitdie("git_commit_id");
		}
		parent_oid_str = git_oid_tostr_s(parent_oid);
		if (!parent_oid_str) {
			gitdie("git_oid_tostr_s");
		}
	}

	oid = git_commit_id(commit);
	if (!oid) {
		gitdie("git_commit_id");
	}

	oid_str = git_oid_tostr_s(oid);
	if (!oid_str) {
		gitdie("git_oid_tostr_s");
	}

	if (git_commit_tree(&tree, commit) < 0) {
		gitdie("git_commit_tree");
	}

	if (git_diff_tree_to_tree(&diff, conf->repo, parent_tree,
			tree, NULL) < 0) {
		gitdie("git_diff_tree_to_tree");
	}

	branch_path(file_base_path, sizeof(file_base_path), conf, br,
		RS_LOG_ROOT, oid_str);
	if (!path_ext(file_path, sizeof(file_path), file_base_path, "html")) {
		die("file path too long %s.html", file_base_path);
	}

	file = page_begin(conf, file_path, oid_str, false);

	fputs("<pre>", file);
	if (git_diff_print(diff, GIT_DIFF_FORMAT_PATCH,
			print_diff_line, file) < 0) {
		gitdie("git_diff_print");
	}
	fputs("</pre>", file);

	page_end(file, file_path);

	git_diff_free(diff);
	git_tree_free(tree);
	git_tree_free(parent_tree);
	git_commit_free(parent);
}

static void
process_commits(const struct repostead_config *conf,
	const struct repostead_branch *br, const git_oid *commit_oid)
{
	char log_path[RS_PATH_MAX] = "";
	const char *index_file_name = "index.html";
	char index_file_path[RS_PATH_MAX] = "";
	FILE *index_file = NULL;
	git_revwalk *walker = NULL;
	git_oid oid;
	int error = 0;

	branch_path(log_path, sizeof(log_path), conf, br, RS_LOG_ROOT, "");
	xmkdir(log_path);

	xpath_join(index_file_path, sizeof(index_file_path),
		log_path, index_file_name);
	index_file = page_begin(conf, index_file_path, br->name, false);

	if (git_revwalk_new(&walker, conf->repo) < 0) {
		gitdie("git_revwalk_new");
	}
	if (git_revwalk_push(walker, commit_oid) < 0) {
		gitdie("git_revwalk_push");
	}

	fputs("<table class=\"commit-list\">", index_file);
	while ((error = git_revwalk_next(&oid, walker)) == 0) {
		git_commit *c = NULL;
		if (git_commit_lookup(&c, conf->repo, &oid) == 0) {
			const char *summary = git_commit_summary(c);
			const git_signature *author = git_commit_author(c);
			const char *oid_str = git_oid_tostr_s(&oid);

			if (!oid_str) {
				gitdie("git_oid_tostr_s");
			}
			fputs("<tr class=\"commit\">", index_file);
			if (author) {
				struct tm tm;
				char tbuf[11];
				git_time_t sec = author->when.time;
				int off = author->when.offset;
				time_t t = (time_t)(sec + (git_time_t)off * 60);
				gmtime_r(&t, &tm);
				strftime(tbuf, sizeof(tbuf), "%Y-%m-%d", &tm);
				fputs("<td class=\"date\">", index_file);
				fputs(tbuf, index_file);
				fputs("</td>", index_file);
			}
			fputs("<td class=\"summary\"><a href=\"", index_file);
			url_enc(index_file, oid_str);
			fputs(".html\">", index_file);
			html_esc(index_file, summary ? summary : "(no message)");
			fputs("</a></td>", index_file);
			if (author) {
				fputs("<td class=\"author\">", index_file);
				html_esc(index_file, author->name ? author->name : "");
				fputs("</td>", index_file);
			}
			fputs("</tr>", index_file);
			process_commit(conf, br, c);
			git_commit_free(c);
		} else {
			gitdie("git_commit_lookup");
		}
	}
	fputs("</table>", index_file);

	if (error != GIT_ITEROVER) {
		gitdie("git_revwalk_next");
	}

	git_revwalk_free(walker);

	page_end(index_file, index_file_path);
}

NODISCARD
static git_tree *
process_branch(const struct repostead_config *conf,
	const char *name, const char *dir, const git_oid *tip_oid)
{
	git_commit *tip = NULL;
	git_tree *tree = NULL;
	struct repostead_branch br;

	memset(&br, 0, sizeof(br));

	if (git_commit_lookup(&tip, conf->repo, tip_oid) < 0) {
		gitdie("git_commit_lookup");
	}
	if (git_commit_tree(&tree, tip) < 0) {
		gitdie("git_commit_tree");
	}

	br.name = name;
	br.tree = tree;
	xpath_join(br.dir, sizeof(br.dir), conf->out_path, dir);

	/* mkdirs in case branch name contains '/' */
	xmkdirs(br.dir);

	process_tree(conf, &br, br.tree, br.name, "");
	process_commits(conf, &br, tip_oid);

	git_commit_free(tip);
	return tree;
}

static int
read_desc_file(char *dest, size_t dsize, const char *git_dir)
{
	const char *desc_file_name = "description";
	char desc_file_path[RS_PATH_MAX] = "";
	FILE *fp = NULL;
	size_t n = 0;
	bool truncated = false;

	if (dsize == 0) {
		return -1;
	}
	dest[0] = 0;

	if (path_join(desc_file_path, sizeof(desc_file_path),
			git_dir, desc_file_name)) {
		fp = fopen(desc_file_path, "rb");
		if (fp) {
			n = fread(dest, 1, dsize - 1, fp);
			if (ferror(fp)) {
				fclose(fp);
				dest[0] = 0;
				warn("error reading repo description file, ignoring");
				return -1;
			}
			truncated = (n == dsize - 1) && (fgetc(fp) != EOF);
			fclose(fp);
			dest[n] = 0;
			return truncated ? -2 : 0;
		} else {
			warn("failed to open repo description file for reading: %s",
				strerror(errno));
			return -1;
		}
	} else {
		warn("repo description file path too long, ignoring");
		return -1;
	}
}

static void
process_repo(struct repostead_config *conf)
{
	char repo_desc[RS_PATH_MAX] = "";
	const char *index_file_name = "index.html";
	char index_file_path[RS_PATH_MAX] = "";
	FILE *index_file = NULL;
	git_branch_iterator *brit = NULL;
	git_branch_t brty;
	git_reference *ref = NULL;
	git_tree *head_tree = NULL;
	int error = 0;

	if (git_libgit2_init() < 0) {
		gitdie("git_libgit2_init");
	}
	if (git_repository_open(&conf->repo, conf->repo_path) < 0) {
		gitdie("git_repository_open");
	}

	conf->repo_git_dir = git_repository_commondir(conf->repo);
	read_desc_file(repo_desc, sizeof(repo_desc), conf->repo_git_dir);
	conf->repo_desc = repo_desc;

	xpath_join(index_file_path, sizeof(index_file_path),
			conf->out_path, index_file_name);
	index_file = page_begin(conf, index_file_path, conf->repo_name, true);

	if (git_branch_iterator_new(
			&brit, conf->repo, GIT_BRANCH_LOCAL) < 0) {
		gitdie("git_branch_iterator_new");
	}

	fputs("<h2>branches</h2><table class=\"branch-list\">", index_file);
	while ((error = git_branch_next(&ref, &brty, brit)) == 0) {
		const char *brnm = NULL;
		const git_oid *tip = git_reference_target(ref);
		bool is_head = (git_branch_is_head(ref) == 1);

		if (git_branch_name(&brnm, ref) < 0) {
			warn("failed to get branch name, skipping");
		} else if (!branch_name_ok(brnm)) {
			warn("unsafe branch name, skipping");
		}
		fputs("<tr>", index_file);
		if (is_head) {
			fputs("<td class=\"head\"><b>", index_file);
			html_esc(index_file, brnm);
			fputs("</b></td>", index_file);
		} else {
			fputs("<td>", index_file);
			html_esc(index_file, brnm);
			fputs("</td>", index_file);
		}
		if (tip) {
			fputs("<td><a href=\"", index_file);
			url_enc(index_file, brnm);
			fputc('/', index_file);
			url_enc(index_file, RS_TREE_ROOT);
			fputs("/\">tree</a></td>", index_file);
			fputs("<td><a href=\"", index_file);
			url_enc(index_file, brnm);
			fputc('/', index_file);
			url_enc(index_file, RS_LOG_ROOT);
			fputs("/\">log</a></td>", index_file);

			head_tree = process_branch(conf, brnm, brnm, tip);
			if (!is_head) {
				git_tree_free(head_tree);
				head_tree = NULL;
			}
		}
		fputs("</tr>", index_file);
		git_reference_free(ref);
	}
	fputs("</table>", index_file);

	if (error != GIT_ITEROVER) {
		gitdie("git_branch_next");
	}

	if (head_tree) {
		tree_readme(index_file, conf, head_tree);
	}

	page_end(index_file, index_file_path);

	git_tree_free(head_tree);
	git_branch_iterator_free(brit);
	git_repository_free(conf->repo);
	conf->repo = NULL;
	conf->repo_desc = NULL;
	conf->repo_git_dir = NULL;
	git_libgit2_shutdown();
}


NORETURN
static void
usage(FILE *out, const char *prog, int status)
{
	fprintf(out,
		"Usage: %s [OPTIONS] repo_path\n"
		"Arguments:\n"
		"  repo_path     path to repository\n"
		"Options:\n"
		"  -u clone_url  repository clone URL\n"
		"  -h            show this help and exit\n"
		"  -v            show version and exit\n",
		prog);
	exit(status);
}

int
main(int argc, char **argv)
{
	const char *prog = argv[0] ? argv[0] : RS_NAME;
	int c = 0;
	char *clone_url = "";
	char *repo_path = NULL;
	char out_path[RS_PATH_MAX] = "";
	char repo_name[RS_PATH_MAX] = "";
	struct repostead_config conf; /* zeroed below */

	while ((c = getopt(argc, argv, ":u:hv")) != -1) {
		switch (c) {
		case 'u':
			clone_url = optarg;
			break;
		case 'h':
			usage(stdout, prog, EXIT_SUCCESS);
		case 'v':
			printf("%s %s\n", prog, RS_VERSION);
			return EXIT_SUCCESS;
		case ':':
			fprintf(stderr, "%s: option -%c requires an argument\n",
				prog, optopt);
			usage(stderr, prog, EXIT_FAILURE);
		case '?':
		default:
			fprintf(stderr, "%s: unknown option -%c\n",
				prog, optopt);
			usage(stderr, prog, EXIT_FAILURE);
		}
	}
	argc -= optind;
	argv += optind;

	if (argc != 1) {
		fprintf(stderr, "%s: expected one argument, got %d\n",
			prog, argc);
		usage(stderr, prog, EXIT_FAILURE);
	}

	repo_path = realpath(argv[0], NULL);
	if (!repo_path) {
		die("failed to resolve path %s: %s", argv[0], strerror(errno));
	}

	if (!getcwd(out_path, sizeof(out_path))) {
		die("failed to getcwd(): %s", strerror(errno));
	}

	memset(&conf, 0, sizeof(conf));
	conf.clone_url = clone_url;
	conf.repo_path = repo_path;
	conf.out_path = out_path;

	repo_name_from_path(repo_name, sizeof(repo_name), conf.repo_path);
	conf.repo_name = repo_name;
	conf.repo_git_dir = ""; /* will be set in process_repo() */
	conf.repo_desc = ""; /* read from .git/description later */

	process_repo(&conf);

	free(repo_path);
	return EXIT_SUCCESS;
}
