Lindenii Project Forge
Login

server

Lindenii Forge’s main backend daemon
Commit info
ID
14326ba9be276d2649b4681d3ebed1c32f65013f
Author
Runxi Yu <me@runxiyu.org>
Author date
Thu, 13 Feb 2025 01:28:35 +0800
Committer
Runxi Yu <me@runxiyu.org>
Committer date
Thu, 13 Feb 2025 01:28:35 +0800
Actions
_header.html: Add header
package main

import (
	"net/http"
)

func get_user_info_from_request(r *http.Request) (id int, username string, err error) {
	session_cookie, err := r.Cookie("session")
	if err != nil {
		return
	}

	err = database.QueryRow(r.Context(), "SELECT user_id, username FROM users u JOIN sessions s ON u.id = s.user_id WHERE s.session_id = $1;", session_cookie.Value).Scan(&id, &username)

	return
}
package main

import (
	"net/http"
)

func handle_group_repos(w http.ResponseWriter, r *http.Request, params map[string]string) {
	data := make(map[string]any)
	data["global"] = global_data
func handle_group_repos(w http.ResponseWriter, r *http.Request, params map[string]any) {
	group_name := params["group_name"]
	data["group_name"] = group_name

	var names []string
	rows, err := database.Query(r.Context(), "SELECT r.name FROM repos r JOIN groups g ON r.group_id = g.id WHERE g.name = $1;", group_name)
	if err != nil {
		_, _ = w.Write([]byte("Error getting groups: " + err.Error()))
		return
	}
	defer rows.Close()

	for rows.Next() {
		var name string
		if err := rows.Scan(&name); err != nil {
			_, _ = w.Write([]byte("Error scanning row: " + err.Error()))
			return
		}
		names = append(names, name)
	}

	if err := rows.Err(); err != nil {
		_, _ = w.Write([]byte("Error iterating over rows: " + err.Error()))
		return
	}

	data["repos"] = names
	params["repos"] = names

	err = templates.ExecuteTemplate(w, "group_repos", data)
	err = templates.ExecuteTemplate(w, "group_repos", params)
	if err != nil {
		_, _ = w.Write([]byte("Error rendering template: " + err.Error()))
		return
	}
}
package main

import (
	"net/http"
)

func handle_index(w http.ResponseWriter, r *http.Request) {
	data := make(map[string]any)
	data["global"] = global_data

func handle_index(w http.ResponseWriter, r *http.Request, params map[string]any) {
	rows, err := database.Query(r.Context(), "SELECT name FROM groups")
	if err != nil {
		_, _ = w.Write([]byte("Error querying groups: " + err.Error()))
		return
	}
	defer rows.Close()

	groups := []string{}
	for rows.Next() {
		var groupName string
		if err := rows.Scan(&groupName); err != nil {
			_, _ = w.Write([]byte("Error scanning group name: " + err.Error()))
			return
		}
		groups = append(groups, groupName)
	}

	if err := rows.Err(); err != nil {
		_, _ = w.Write([]byte("Error iterating over rows: " + err.Error()))
		return
	}

	data["groups"] = groups
	params["groups"] = groups

	err = templates.ExecuteTemplate(w, "index", data)
	err = templates.ExecuteTemplate(w, "index", params)
	if err != nil {
		_, _ = w.Write([]byte("Error rendering template: " + err.Error()))
		return
	}
}
package main

import (
	"net/http"
	"strings"

	"github.com/go-git/go-git/v5/plumbing"
	"github.com/go-git/go-git/v5/plumbing/filemode"
	"github.com/go-git/go-git/v5/plumbing/format/diff"
	"go.lindenii.runxiyu.org/lindenii-common/misc"
)

type usable_file_patch struct {
	From   diff.File
	To     diff.File
	Chunks []diff.Chunk
}

func handle_repo_commit(w http.ResponseWriter, r *http.Request, params map[string]string) {
	data := make(map[string]any)
	data["global"] = global_data
	group_name, repo_name, commit_id_specified_string := params["group_name"], params["repo_name"], params["commit_id"]
	data["group_name"], data["repo_name"] = group_name, repo_name
func handle_repo_commit(w http.ResponseWriter, r *http.Request, params map[string]any) {
	group_name, repo_name, commit_id_specified_string := params["group_name"].(string), params["repo_name"].(string), params["commit_id"].(string)
	repo, err := open_git_repo(r.Context(), group_name, repo_name)
	if err != nil {
		_, _ = w.Write([]byte("Error opening repo: " + err.Error()))
		return
	}
	commit_id_specified_string_without_suffix := strings.TrimSuffix(commit_id_specified_string, ".patch")
	commit_id := plumbing.NewHash(commit_id_specified_string_without_suffix)
	commit_object, err := repo.CommitObject(commit_id)
	if err != nil {
		_, _ = w.Write([]byte("Error getting commit object: " + err.Error()))
		return
	}
	if commit_id_specified_string_without_suffix != commit_id_specified_string {
		patch, err := format_patch_from_commit(commit_object)
		if err != nil {
			_, _ = w.Write([]byte("Error formatting patch: " + err.Error()))
			return
		}
		_, _ = w.Write([]byte(patch))
		return
	}
	commit_id_string := commit_object.Hash.String()

	if commit_id_string != commit_id_specified_string {
		http.Redirect(w, r, commit_id_string, http.StatusSeeOther)
		return
	}

	data["commit_object"] = commit_object
	data["commit_id"] = commit_id_string
	params["commit_object"] = commit_object
	params["commit_id"] = commit_id_string

	parent_commit_hash, patch, err := get_patch_from_commit(commit_object)
	if err != nil {
		_, _ = w.Write([]byte("Error getting patch from commit: " + err.Error()))
		return
	}
	data["parent_commit_hash"] = parent_commit_hash.String()
	data["patch"] = patch
	params["parent_commit_hash"] = parent_commit_hash.String()
	params["patch"] = patch

	// TODO: Remove unnecessary context
	// TODO: Prepend "+"/"-"/" " instead of solely distinguishing based on color
	usable_file_patches := make([]usable_file_patch, 0)
	for _, file_patch := range patch.FilePatches() {
		from, to := file_patch.Files()
		if from == nil {
			from = fake_diff_file_null
		}
		if to == nil {
			to = fake_diff_file_null
		}
		usable_file_patch := usable_file_patch{
			Chunks: file_patch.Chunks(),
			From:   from,
			To:     to,
		}
		usable_file_patches = append(usable_file_patches, usable_file_patch)
	}
	data["file_patches"] = usable_file_patches
	params["file_patches"] = usable_file_patches

	err = templates.ExecuteTemplate(w, "repo_commit", data)
	err = templates.ExecuteTemplate(w, "repo_commit", params)
	if err != nil {
		_, _ = w.Write([]byte("Error rendering template: " + err.Error()))
		return
	}
}

type fake_diff_file struct {
	hash plumbing.Hash
	mode filemode.FileMode
	path string
}

func (f fake_diff_file) Hash() plumbing.Hash {
	return f.hash
}

func (f fake_diff_file) Mode() filemode.FileMode {
	return f.mode
}

func (f fake_diff_file) Path() string {
	return f.path
}

var fake_diff_file_null = fake_diff_file{
	hash: plumbing.NewHash("e69de29bb2d1d6434b8b29ae775ad8c2e48c5391"),
	mode: misc.First_or_panic(filemode.New("100644")),
	path: "",
}
package main

import (
	"net/http"
	"net/url"
)

func handle_repo_index(w http.ResponseWriter, r *http.Request, params map[string]string) {
	data := make(map[string]any)
	data["global"] = global_data
	group_name, repo_name := params["group_name"], params["repo_name"]
	data["group_name"], data["repo_name"] = group_name, repo_name
func handle_repo_index(w http.ResponseWriter, r *http.Request, params map[string]any) {
	group_name, repo_name := params["group_name"].(string), params["repo_name"].(string)
	repo, err := open_git_repo(r.Context(), group_name, repo_name)
	if err != nil {
		_, _ = w.Write([]byte("Error opening repo: " + err.Error()))
		return
	}
	head, err := repo.Head()
	if err != nil {
		_, _ = w.Write([]byte("Error getting repo HEAD: " + err.Error()))
		return
	}
	data["ref"] = head.Name().Short()
	params["ref"] = head.Name().Short()
	head_hash := head.Hash()
	recent_commits, err := get_recent_commits(repo, head_hash, 3)
	if err != nil {
		_, _ = w.Write([]byte("Error getting recent commits: " + err.Error()))
		return
	}
	data["commits"] = recent_commits
	params["commits"] = recent_commits
	commit_object, err := repo.CommitObject(head_hash)
	if err != nil {
		_, _ = w.Write([]byte("Error getting commit object: " + err.Error()))
		return
	}
	tree, err := commit_object.Tree()
	if err != nil {
		_, _ = w.Write([]byte("Error getting file tree: " + err.Error()))
		return
	}

	data["readme_filename"], data["readme"] = render_readme_at_tree(tree)
	data["files"] = build_display_git_tree(tree)
	params["readme_filename"], params["readme"] = render_readme_at_tree(tree)
	params["files"] = build_display_git_tree(tree)

	data["clone_url"] = "ssh://" + r.Host + "/" + url.PathEscape(params["group_name"]) + "/:/repos/" + url.PathEscape(params["repo_name"])
	params["clone_url"] = "ssh://" + r.Host + "/" + url.PathEscape(group_name) + "/:/repos/" + url.PathEscape(repo_name)

	err = templates.ExecuteTemplate(w, "repo_index", data)
	err = templates.ExecuteTemplate(w, "repo_index", params)
	if err != nil {
		_, _ = w.Write([]byte("Error rendering template: " + err.Error()))
		return
	}
}
package main

import (
	"net/http"
	"net/url"
)

func handle_repo_info(w http.ResponseWriter, r *http.Request, params map[string]string) {
	http.Error(w, "\x1b[1;93mHi! We do not support Git operations over HTTP yet.\x1b[0m\n\x1b[1;93mMeanwhile, please use ssh by simply replacing the scheme with \"ssh://\":\x1b[0m\n\x1b[1;93mssh://"+r.Host+"/"+url.PathEscape(params["group_name"])+"/:/repos/"+url.PathEscape(params["repo_name"])+"\x1b[0m", http.StatusNotImplemented)
func handle_repo_info(w http.ResponseWriter, r *http.Request, params map[string]any) {
	http.Error(w, "\x1b[1;93mHi! We do not support Git operations over HTTP yet.\x1b[0m\n\x1b[1;93mMeanwhile, please use ssh by simply replacing the scheme with \"ssh://\":\x1b[0m\n\x1b[1;93mssh://"+r.Host+"/"+url.PathEscape(params["group_name"].(string))+"/:/repos/"+url.PathEscape(params["repo_name"].(string))+"\x1b[0m", http.StatusNotImplemented)
}
package main

import (
	"net/http"

	"github.com/go-git/go-git/v5/plumbing"
)

// TODO: I probably shouldn't include *all* commits here...
func handle_repo_log(w http.ResponseWriter, r *http.Request, params map[string]string) {
	data := make(map[string]any)
	data["global"] = global_data
	group_name, repo_name, ref_name := params["group_name"], params["repo_name"], params["ref"]
	data["group_name"], data["repo_name"], data["ref"] = group_name, repo_name, ref_name
func handle_repo_log(w http.ResponseWriter, r *http.Request, params map[string]any) {
	group_name, repo_name, ref_name := params["group_name"].(string), params["repo_name"].(string), params["ref"].(string)
	repo, err := open_git_repo(r.Context(), group_name, repo_name)
	if err != nil {
		_, _ = w.Write([]byte("Error opening repo: " + err.Error()))
		return
	}
	ref, err := repo.Reference(plumbing.NewBranchReferenceName(ref_name), true)
	if err != nil {
		_, _ = w.Write([]byte("Error getting repo reference: " + err.Error()))
		return
	}
	ref_hash := ref.Hash()
	commits, err := get_recent_commits(repo, ref_hash, -1)
	if err != nil {
		_, _ = w.Write([]byte("Error getting recent commits: " + err.Error()))
		return
	}
	data["commits"] = commits
	params["commits"] = commits

	err = templates.ExecuteTemplate(w, "repo_log", data)
	err = templates.ExecuteTemplate(w, "repo_log", params)
	if err != nil {
		_, _ = w.Write([]byte("Error rendering template: " + err.Error()))
		return
	}
}
package main

import (
	"errors"
	"net/http"
	"path"
	"strings"

	"github.com/go-git/go-git/v5/plumbing/object"
)

func handle_repo_raw(w http.ResponseWriter, r *http.Request, params map[string]string) {
	data := make(map[string]any)
	data["global"] = global_data
	raw_path_spec := params["rest"]
	group_name, repo_name, path_spec := params["group_name"], params["repo_name"], strings.TrimSuffix(raw_path_spec, "/")
func handle_repo_raw(w http.ResponseWriter, r *http.Request, params map[string]any) {
	raw_path_spec := params["rest"].(string)
	group_name, repo_name, path_spec := params["group_name"].(string), params["repo_name"].(string), strings.TrimSuffix(raw_path_spec, "/")

	ref_type, ref_name, err := get_param_ref_and_type(r)
	if err != nil {
		if errors.Is(err, err_no_ref_spec) {
			ref_type = "head"
		} else {
			_, _ = w.Write([]byte("Error querying ref type: " + err.Error()))
			return
		}
	}

	data["ref_type"], data["ref"], data["group_name"], data["repo_name"], data["path_spec"] = ref_type, ref_name, group_name, repo_name, path_spec
	params["ref_type"], params["ref"], params["path_spec"] = ref_type, ref_name, path_spec

	repo, err := open_git_repo(r.Context(), group_name, repo_name)
	if err != nil {
		_, _ = w.Write([]byte("Error opening repo: " + err.Error()))
		return
	}

	ref_hash, err := get_ref_hash_from_type_and_name(repo, ref_type, ref_name)
	if err != nil {
		_, _ = w.Write([]byte("Error getting ref hash: " + err.Error()))
		return
	}

	commit_object, err := repo.CommitObject(ref_hash)
	if err != nil {
		_, _ = w.Write([]byte("Error getting commit object: " + err.Error()))
		return
	}
	tree, err := commit_object.Tree()
	if err != nil {
		_, _ = w.Write([]byte("Error getting file tree: " + err.Error()))
		return
	}

	var target *object.Tree
	if path_spec == "" {
		target = tree
	} else {
		target, err = tree.Tree(path_spec)
		if err != nil {
			file, err := tree.File(path_spec)
			if err != nil {
				_, _ = w.Write([]byte("Error retrieving path: " + err.Error()))
				return
			}
			if len(raw_path_spec) != 0 && raw_path_spec[len(raw_path_spec)-1] == '/' {
				http.Redirect(w, r, "../"+path_spec, http.StatusSeeOther)
				return
			}
			file_contents, err := file.Contents()
			if err != nil {
				_, _ = w.Write([]byte("Error reading file: " + err.Error()))
				return
			}
			_, _ = w.Write([]byte(file_contents))
			return
		}
	}

	if len(raw_path_spec) != 0 && raw_path_spec[len(raw_path_spec)-1] != '/' {
		http.Redirect(w, r, path.Base(path_spec)+"/", http.StatusSeeOther)
		return
	}

	data["files"] = build_display_git_tree(target)
	params["files"] = build_display_git_tree(target)

	err = templates.ExecuteTemplate(w, "repo_raw_dir", data)
	err = templates.ExecuteTemplate(w, "repo_raw_dir", params)
	if err != nil {
		_, _ = w.Write([]byte("Error rendering template: " + err.Error()))
		return
	}
}
package main

import (
	"bytes"
	"errors"
	"html/template"
	"net/http"
	"path"
	"strings"

	chroma_formatters_html "github.com/alecthomas/chroma/v2/formatters/html"
	chroma_lexers "github.com/alecthomas/chroma/v2/lexers"
	chroma_styles "github.com/alecthomas/chroma/v2/styles"
	"github.com/go-git/go-git/v5/plumbing/object"
)

func handle_repo_tree(w http.ResponseWriter, r *http.Request, params map[string]string) {
	data := make(map[string]any)
	data["global"] = global_data
	raw_path_spec := params["rest"]
	group_name, repo_name, path_spec := params["group_name"], params["repo_name"], strings.TrimSuffix(raw_path_spec, "/")
func handle_repo_tree(w http.ResponseWriter, r *http.Request, params map[string]any) {
	raw_path_spec := params["rest"].(string)
	group_name, repo_name, path_spec := params["group_name"].(string), params["repo_name"].(string), strings.TrimSuffix(raw_path_spec, "/")
	ref_type, ref_name, err := get_param_ref_and_type(r)
	if err != nil {
		if errors.Is(err, err_no_ref_spec) {
			ref_type = "head"
		} else {
			_, _ = w.Write([]byte("Error querying ref type: " + err.Error()))
			return
		}
	}
	data["ref_type"], data["ref"], data["group_name"], data["repo_name"], data["path_spec"] = ref_type, ref_name, group_name, repo_name, path_spec
	params["ref_type"], params["ref"], params["path_spec"] = ref_type, ref_name, path_spec
	repo, err := open_git_repo(r.Context(), group_name, repo_name)
	if err != nil {
		_, _ = w.Write([]byte("Error opening repo: " + err.Error()))
		return
	}
	ref_hash, err := get_ref_hash_from_type_and_name(repo, ref_type, ref_name)
	if err != nil {
		_, _ = w.Write([]byte("Error getting ref hash: " + err.Error()))
		return
	}
	commit_object, err := repo.CommitObject(ref_hash)
	if err != nil {
		_, _ = w.Write([]byte("Error getting commit object: " + err.Error()))
		return
	}
	tree, err := commit_object.Tree()
	if err != nil {
		_, _ = w.Write([]byte("Error getting file tree: " + err.Error()))
		return
	}

	var target *object.Tree
	if path_spec == "" {
		target = tree
	} else {
		target, err = tree.Tree(path_spec)
		if err != nil {
			file, err := tree.File(path_spec)
			if err != nil {
				_, _ = w.Write([]byte("Error retrieving path: " + err.Error()))
				return
			}
			if len(raw_path_spec) != 0 && raw_path_spec[len(raw_path_spec)-1] == '/' {
				http.Redirect(w, r, "../"+path_spec, http.StatusSeeOther)
				return
			}
			file_contents, err := file.Contents()
			if err != nil {
				_, _ = w.Write([]byte("Error reading file: " + err.Error()))
				return
			}
			lexer := chroma_lexers.Match(path_spec)
			if lexer == nil {
				lexer = chroma_lexers.Fallback
			}
			iterator, err := lexer.Tokenise(nil, file_contents)
			if err != nil {
				_, _ = w.Write([]byte("Error tokenizing code: " + err.Error()))
				return
			}
			var formatted_unencapsulated bytes.Buffer
			style := chroma_styles.Get("autumn")
			formatter := chroma_formatters_html.New(chroma_formatters_html.WithClasses(true), chroma_formatters_html.TabWidth(8))
			err = formatter.Format(&formatted_unencapsulated, style, iterator)
			if err != nil {
				_, _ = w.Write([]byte("Error formatting code: " + err.Error()))
				return
			}
			formatted_encapsulated := template.HTML(formatted_unencapsulated.Bytes())
			data["file_contents"] = formatted_encapsulated
			params["file_contents"] = formatted_encapsulated

			err = templates.ExecuteTemplate(w, "repo_tree_file", data)
			err = templates.ExecuteTemplate(w, "repo_tree_file", params)
			if err != nil {
				_, _ = w.Write([]byte("Error rendering template: " + err.Error()))
				return
			}
			return
		}
	}

	if len(raw_path_spec) != 0 && raw_path_spec[len(raw_path_spec)-1] != '/' {
		http.Redirect(w, r, path.Base(path_spec)+"/", http.StatusSeeOther)
		return
	}

	data["readme_filename"], data["readme"] = render_readme_at_tree(target)
	data["files"] = build_display_git_tree(target)
	params["readme_filename"], params["readme"] = render_readme_at_tree(target)
	params["files"] = build_display_git_tree(target)

	err = templates.ExecuteTemplate(w, "repo_tree_dir", data)
	err = templates.ExecuteTemplate(w, "repo_tree_dir", params)
	if err != nil {
		_, _ = w.Write([]byte("Error rendering template: " + err.Error()))
		return
	}
}
package main

import (
	"errors"
	"fmt"
	"net/http"
	"strings"
)

type http_router_t struct{}

func (router *http_router_t) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	segments, _, err := parse_request_uri(r.RequestURI)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	non_empty_last_segments_len := len(segments)
	dir_mode := false
	if segments[len(segments)-1] == "" {
		non_empty_last_segments_len--
		dir_mode = true
	}

	if segments[0] == ":" {
		if len(segments) < 2 {
			http.Error(w, "Blank system endpoint", http.StatusNotFound)
			return
		} else if len(segments) == 2 && !dir_mode {
			http.Redirect(w, r, r.URL.Path+"/", http.StatusSeeOther)
			return
		}

		switch segments[1] {
		case "static":
			static_handler.ServeHTTP(w, r)
		case "source":
			source_handler.ServeHTTP(w, r)
		default:
			http.Error(w, fmt.Sprintf("Unknown system module type: %s", segments[1]), http.StatusNotFound)
		}
		return
	}

	params := make(map[string]any)
	params["global"] = global_data
	var _user_id int
	_user_id, params["username"], err = get_user_info_from_request(r)
	if _user_id == 0 {
		params["user_id"] = ""
	} else {
		params["user_id"] = string(_user_id)
	}

	fmt.Printf("%#v\n", params)

	separator_index := -1
	for i, part := range segments {
		if part == ":" {
			separator_index = i
			break
		}
	}
	non_empty_last_segments_len := len(segments)
	dir_mode := false
	if segments[len(segments)-1] == "" {
		non_empty_last_segments_len--
		dir_mode = true
	}

	params := make(map[string]string)
	_ = params
	switch {
	case non_empty_last_segments_len == 0:
		handle_index(w, r)
		handle_index(w, r, params)
	case separator_index == -1:
		http.Error(w, "Group indexing hasn't been implemented yet", http.StatusNotImplemented)
	case non_empty_last_segments_len == separator_index+1:
		http.Error(w, "Group root hasn't been implemented yet", http.StatusNotImplemented)
	case non_empty_last_segments_len == separator_index+2:
		if !dir_mode {
			http.Redirect(w, r, r.URL.Path+"/", http.StatusSeeOther)
			return
		}
		module_type := segments[separator_index+1]
		params["group_name"] = segments[0]
		switch module_type {
		case "repos":
			handle_group_repos(w, r, params)
		default:
			http.Error(w, fmt.Sprintf("Unknown module type: %s", module_type), http.StatusNotFound)
		}
	default:
		module_type := segments[separator_index+1]
		module_name := segments[separator_index+2]
		params["group_name"] = segments[0]
		switch module_type {
		case "repos":
			params["repo_name"] = module_name
			// TODO: subgroups
			if non_empty_last_segments_len == separator_index+3 {
				if !dir_mode {
					http.Redirect(w, r, r.URL.Path+"/", http.StatusSeeOther)
					return
				}
				handle_repo_index(w, r, params)
				return
			}
			repo_feature := segments[separator_index+3]
			switch repo_feature {
			case "info":
				handle_repo_info(w, r, params)
			case "tree":
				params["rest"] = strings.Join(segments[separator_index+4:], "/")
				handle_repo_tree(w, r, params)
			case "raw":
				params["rest"] = strings.Join(segments[separator_index+4:], "/")
				handle_repo_raw(w, r, params)
			case "log":
				if non_empty_last_segments_len != separator_index+5 {
					http.Error(w, "Too many parameters", http.StatusBadRequest)
					return
				}
				if dir_mode {
					http.Redirect(w, r, strings.TrimSuffix(r.URL.Path, "/"), http.StatusSeeOther)
					return
				}
				params["ref"] = segments[separator_index+4]
				handle_repo_log(w, r, params)
			case "commit":
				if dir_mode {
					http.Redirect(w, r, strings.TrimSuffix(r.URL.Path, "/"), http.StatusSeeOther)
					return
				}
				params["commit_id"] = segments[separator_index+4]
				handle_repo_commit(w, r, params)
			default:
				http.Error(w, fmt.Sprintf("Unknown repo feature: %s", repo_feature), http.StatusNotFound)
			}
		default:
			http.Error(w, fmt.Sprintf("Unknown module type: %s", module_type), http.StatusNotFound)
		}
	}
}

var err_bad_request = errors.New("Bad Request")
CREATE TABLE groups (
	id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
	name TEXT NOT NULL UNIQUE 
);

CREATE TABLE repos (
	id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
	group_id INTEGER NOT NULL REFERENCES groups(id) ON DELETE RESTRICT, -- I mean, should be CASCADE but deleting Git repos on disk also needs to be considered
	name TEXT NOT NULL,
	UNIQUE(group_id, name),
	description TEXT,
	filesystem_path TEXT
);

CREATE TABLE ticket_trackers (
	id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
	group_id INTEGER NOT NULL REFERENCES groups(id) ON DELETE RESTRICT,
	name TEXT NOT NULL,
	UNIQUE(group_id, name),
	description TEXT
);

CREATE TABLE tickets (
	id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
	tracker_id INTEGER NOT NULL REFERENCES ticket_trackers(id) ON DELETE CASCADE,
	title TEXT NOT NULL,
	description TEXT
);

CREATE TABLE mailing_lists (
	id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
	group_id INTEGER NOT NULL REFERENCES groups(id) ON DELETE RESTRICT,
	name TEXT NOT NULL,
	UNIQUE(group_id, name),
	description TEXT
);

CREATE TABLE emails (
	id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
	list_id INTEGER NOT NULL REFERENCES mailing_lists(id) ON DELETE CASCADE,
	title TEXT NOT NULL,
	sender TEXT NOT NULL,
	date TIMESTAMP NOT NULL,
	content BYTEA NOT NULL
);

CREATE TABLE users (
	id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
	username TEXT NOT NULL UNIQUE,
	password_algorithm TEXT NOT NULL CHECK (password_algorithm in ('argon2id')),
	password TEXT NOT NULL
);

CREATE TABLE sessions (
	user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
	session_id TEXT NOT NULL,
	PRIMARY KEY (user_id, session_id)
);

CREATE TABLE merge_requests (
	id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
	repo_id INTEGER NOT NULL REFERENCES repos(id) ON DELETE CASCADE,
	creator INTEGER REFERENCES users(id) ON DELETE SET NULL,
	source_ref TEXT NOT NULL,
	destination_branch TEXT NOT NULL,
	status TEXT NOT NULL CHECK (status IN ('open', 'merged', 'closed')),
	created_at TIMESTAMP NOT NULL,
	mailing_list_id INT UNIQUE REFERENCES mailing_lists(id) ON DELETE CASCADE
);

CREATE TABLE ssh_public_keys (
	id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
	user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
	content TEXT NOT NULL,
	UNIQUE (user_id, content)
);
{{- define "header" -}}
<div>
	<a href="/">Lindenii Forge</a>
</div>
<div>
	{{ if ne .user_id "" }}
		<a href="/:/user/{{ .user_id }}">{{ .username }}</a>
	{{ else }}
		<a href="/:/login/">Login</a>
	{{ end }}
</div>
{{- end -}}
{{- define "repo_header" -}}
<a href="/">Lindenii Forge</a>
/
<a href="/{{ .group_name }}/">{{ .group_name }}</a>
/
<a href="/{{ .group_name }}/:">:</a>
/
<a href="/{{ .group_name }}/:/repos/">repos</a>
/
<a href="/{{ .group_name }}/:/repos/{{ .repo_name }}/">{{ .repo_name }}</a>
{{- end -}}
{{- define "group_repos" -}}
<!DOCTYPE html>
<html lang="en">
	<head>
		{{ template "head_common" . }}
		<title>Repos in {{ .group_name }} &ndash; Lindenii Forge</title>
	</head>
	<body class="group-repos">
		<header>
			{{ template "header" . }}
		</header>
		<div class="padding-wrapper">
			<h1>
			Repos in {{ .group_name }}
			</h1>
			<ul>
				{{- range .repos }}
					<li>
						<a href="{{ . }}/">{{ . }}</a>
					</li>
				{{- end }}
			</ul>
		</div>
		<footer>
			{{ template "footer" . }}
		</footer>
	</body>
</html>
{{- end -}}
{{- define "index" -}}
<!DOCTYPE html>
<html lang="en">
	<head>
		{{ template "head_common" . }}
		<title>Index &ndash; Lindenii Forge</title>
	</head>
	<body class="index">
		<header>
			{{ template "header" . }}
		</header>
		<div class="padding-wrapper">
			<h1>Lindenii Forge</h1>
			<h2>
				Groups
			</h2>
			<ul>
				{{- range .groups }}
					<li>
						<a href="{{ . }}/:/repos/">{{ . }}</a>
					</li>
				{{- end }}
			</ul>
			<h2>
				Info
			</h2>
			<table class="wide">
				<tbody>
					<tr>
						<th scope="row">SSH Public Key</th>
						<td><code>{{ .global.server_public_key_string }}</code></td>
					</tr>
					<tr>
						<th scope="row">SSH Fingerprint</th>
						<td><code>{{ .global.server_public_key_fingerprint }}</code></td>
					</tr>
				</tbody>
			</table>
		</div>
		<footer>
			{{ template "footer" . }}
		</footer>
	</body>
</html>
{{- end -}}
{{- define "repo_commit" -}}
<!DOCTYPE html>
<html lang="en">
	<head>
		{{ template "head_common" . }}
		<title>{{ .group_name }}/repos/{{ .repo_name }} &ndash; Lindenii Forge</title>
	</head>
	<body class="repo-commit">
		<header>
			{{ template "header" . }}
		</header>
		<header>
			{{ template "repo_header" . }}
		</header>
		<div class="padding-wrapper scroll">
			<table id="commit-info-table">
				<thead>
					<tr class="title-row">
						<th colspan="2">Commit Info</th>
					</tr>
				</thead>
				<tbody>
					<tr>
						<th scope="row">ID</th>
						<td>{{ .commit_id }}</td>
					</tr>
					<tr>
						<th scope="row">Author</th>
						<td>{{ .commit_object.Author.Name }} &lt;<a href="mailto:{{ .commit_object.Author.Email }}">{{ .commit_object.Author.Email }}</a>&gt;</td>
					</tr>
					<tr>
						<th scope="row">Author Date</th>
						<td>{{ .commit_object.Author.When.Format "Mon, 02 Jan 2006 15:04:05 -0700" }}</td>
					</tr>
					<tr>
						<th scope="row">Committer</th>
						<td>{{ .commit_object.Committer.Name }} &lt;<a href="mailto:{{ .commit_object.Committer.Email }}">{{ .commit_object.Committer.Email }}</a>&gt;</td>
					</tr>
					<tr>
						<th scope="row">Committer Date</th>
						<td>{{ .commit_object.Committer.When.Format "Mon, 02 Jan 2006 15:04:05 -0700" }}</td>
					</tr>
					<tr>
						<th scope="row">Message</th>
						<td><pre>{{ .commit_object.Message }}</pre></td>
					</tr>
					<tr>
						<th scope="row">Actions</th>
						<td><pre><a href="{{ .commit_object.Hash }}.patch">Get as Patch</a></pre></td>
					</tr>
				</tbody>
			</table>
		</div>
		<div class="padding-wrapper">
			{{ $parent_commit_hash := .parent_commit_hash }}
			{{ $commit_object := .commit_object }}
			{{ range .file_patches }}
				<div class="file-patch toggle-on-wrapper">
					<input type="checkbox" id="toggle-{{ .From.Hash }}{{ .To.Hash }}" class="file-toggle toggle-on-toggle">
					<label for="toggle-{{ .From.Hash }}{{ .To.Hash }}" class="file-header toggle-on-header">
						<span>
							{{ if eq .From.Path "" }}
								--- /dev/null
							{{ else }}
								--- a/<a href="../tree/{{ .From.Path }}?commit={{ $parent_commit_hash }}">{{ .From.Path }}</a> {{ .From.Mode }}
							{{ end }}
							<br />
							{{ if eq .To.Path "" }}
								+++ /dev/null
							{{ else }}
								+++ b/<a href="../tree/{{ .To.Path }}?commit={{ $commit_object.Hash }}">{{ .To.Path }}</a> {{ .To.Mode }}
							{{ end }}
						</span>
					</label>
					<div class="file-content toggle-on-content scroll">
						{{ range .Chunks }}
							{{ if eq .Type 0 }}
								<pre class="chunk chunk-unchanged">{{ .Content }}</pre>
							{{ else if eq .Type 1 }}
								<pre class="chunk chunk-addition">{{ .Content }}</pre>
							{{ else if eq .Type 2 }}
								<pre class="chunk chunk-deletion">{{ .Content }}</pre>
							{{ else }}
								<pre class="chunk chunk-unknown">{{ .Content }}</pre>
							{{ end }}
						{{ end }}
					</div>
				</div>
			{{ end }}
		</div>
		<footer>
			{{ template "footer" . }}
		</footer>
	</body>
</html>
{{- end -}}
{{- define "repo_index" -}}
<!DOCTYPE html>
<html lang="en">
	<head>
		{{ template "head_common" . }}
		<title>{{ .group_name }}/repos/{{ .repo_name }} &ndash; Lindenii Forge</title>
	</head>
	<body class="repo-index">
		<header>
			{{ template "header" . }}
		</header>
		<header>
			{{ template "repo_header" . }}
		</header>
		<div class="padding-wrapper">
			<table id="repo-info-table">
				<thead>
					<tr class="title-row">
						<th colspan="2">Repo Info</th>
					</tr>
				</thead>
				<tbody>
					<tr>
						<th scope="row">Clone</th>
						<td><code>git clone {{ .clone_url }}</code></td>
					</tr>
				</tbody>
			</table>
		</div>
		<div class="padding-wrapper scroll">
			<input id="toggle-table-recent-commits" type="checkbox" class="toggle-table-off" />
			<table id="recent-commits" class="wide">
				<thead>
					<tr class="title-row">
						<th colspan="3"><label for="toggle-table-recent-commits">Recent Commits (<a href="log/{{ .ref }}/">see all</a>)</label></th>
					</tr>
				</thead>
				<tbody>
					{{- range .commits }}
						<tr>
							<td class="commit-title"><a href="commit/{{ .ID }}">{{ .Message | first_line }}</a></td>
							<td class="commit-author">
								<a class="email-name" href="mailto:{{ .Author.Email }}">{{ .Author.Name }}</a>
							</td>
							<td class="commit-time">
								{{ .Author.When.Format "2006-01-02 15:04:05 -0700" }}
							</td>
						</tr>
					{{- end }}
				</tbody>
			</table>
		</div>
		<div class="padding-wrapper scroll">
			<input id="toggle-table-file-tree" type="checkbox" class="toggle-table-off" />
			<table id="file-tree" class="wide">
				<thead>
					<tr class="title-row">
						<th colspan="3"><label for="toggle-table-file-tree">/ on {{ .ref }}</label></th>
					</tr>
				</thead>
				<tbody>
					{{- $ref := .ref }}
					{{- range .files }}
						<tr>
							<td class="file-mode">{{ .Mode }}</td>
							<td class="file-name"><a href="tree/{{ .Name }}">{{ .Name }}</a>{{ if not .Is_file }}/{{ end }}</td>
							<td class="file-size">{{ .Size }}</td>
						</tr>
					{{- end }}
				</tbody>
			</table>
		</div>
		<div class="padding-wrapper">
			<div id="refs">
			</div>
		</div>
		<div class="padding-wrapper">
			{{ if .readme }}
				<input id="toggle-table-readme" type="checkbox" class="toggle-table-off" />
				<table class="wide">
					<thead>
						<tr class="title-row">
							<th><label for="toggle-table-readme">{{ .readme_filename }}</label></th>
						</tr>
					</thead>
					<tbody>
						<tr>
							<td id="readme">
								{{ .readme -}}
							</td>
						</tr>
					</tbody>
				</table>
			{{ end }}
		</div>
		<footer>
			{{ template "footer" . }}
		</footer>
	</body>
</html>
{{- end -}}
{{- define "repo_log" -}}
<!DOCTYPE html>
<html lang="en">
	<head>
		{{ template "head_common" . }}
		<title>Log of {{ .group_name }}/repos/{{ .repo_name }} &ndash; Lindenii Forge</title>
	</head>
	<body class="repo-log">
		<header>
			{{ template "header" . }}
		</header>
		<header>
			{{ template "repo_header" . }}
		</header>
		<table id="commits" class="wide">
			<thead>
				<tr class="title-row">
					<th colspan="4">Commits on {{ .ref }}</th>
				</tr>
				<tr>
					<th scope="col">ID</th>
					<th scope="col">Title</th>
					<th scope="col">Author</th>
					<th scope="col">Time</th>
				</tr>
			</thead>
			<tbody>
				{{- range .commits }}
					<tr>
						<td class="commit-id"><a href="../commit/{{ .ID }}">{{ .ID }}</a></td>
						<td class="commit-title">{{ .Message | first_line }}</td>
						<td class="commit-author">
							<a class="email-name" href="mailto:{{ .Author.Email }}">{{ .Author.Name }}</a>
						</td>
						<td class="commit-time">
							{{ .Author.When.Format "2006-01-02 15:04:05 -0700" }}
						</td>
					</tr>
				{{- end }}
			</tbody>
		</table>
		<footer>
			{{ template "footer" . }}
		</footer>
	</body>
</html>
{{- end -}}
{{- define "repo_raw_dir" -}}
<!DOCTYPE html>
<html lang="en">
	<head>
		{{ template "head_common" . }}
		<title>{{ .group_name }}/repos/{{ .repo_name }}/{{ .path_spec }}{{ if ne .path_spec "" }}/{{ end }} &ndash; Lindenii Forge</title>
	</head>
	<body class="repo-raw-dir">
		<header>
			{{ template "header" . }}
		</header>
		<header>
			{{ template "repo_header" . }}
		</header>
		<div class="padding-wrapper scroll">
			<table id="file-tree" class="wide">
				<thead>
					<tr class="title-row">
						<th colspan="3">
							(Raw) /{{ .path_spec }}{{ if ne .path_spec "" }}/{{ end }} on {{ .ref }}
						</th>
					</tr>
				</thead>
				<tbody>
					{{- $path_spec := .path_spec }}
					{{- range .files }}
						<tr>
							<td class="file-mode">{{ .Mode }}</td>
							<td class="file-name"><a href="{{ .Name }}{{ if not .Is_file }}/{{ end }}">{{ .Name }}</a>{{ if not .Is_file }}/{{ end }}</td>
							<td class="file-size">{{ .Size }}</td>
						</tr>
					{{- end }}
				</tbody>
			</table>
		</div>
		<div class="padding-wrapper">
			<div id="refs">
			</div>
		</div>
		<footer>
			{{ template "footer" . }}
		</footer>
	</body>
</html>
{{- end -}}
{{- define "repo_tree_dir" -}}
<!DOCTYPE html>
<html lang="en">
	<head>
		{{ template "head_common" . }}
		<title>{{ .group_name }}/repos/{{ .repo_name }}/{{ .path_spec }}{{ if ne .path_spec "" }}/{{ end }} &ndash; Lindenii Forge</title>
	</head>
	<body class="repo-tree-dir">
		<header>
			{{ template "header" . }}
		</header>
		<header>
			{{ template "repo_header" . }}
		</header>
		<div class="padding-wrapper scroll">
			<table id="file-tree" class="wide">
				<thead>
					<tr class="title-row">
						<th colspan="3">
							/{{ .path_spec }}{{ if ne .path_spec "" }}/{{ end }} on {{ .ref }}
						</th>
					</tr>
				</thead>
				<tbody>
					{{- $path_spec := .path_spec }}
					{{- range .files }}
						<tr>
							<td class="file-mode">{{ .Mode }}</td>
							<td class="file-name"><a href="{{ .Name }}{{ if not .Is_file }}/{{ end }}">{{ .Name }}</a>{{ if not .Is_file }}/{{ end }}</td>
							<td class="file-size">{{ .Size }}</td>
						</tr>
					{{- end }}
				</tbody>
			</table>
		</div>
		<div class="padding-wrapper">
			<div id="refs">
			</div>
		</div>
		<div class="padding-wrapper">
			{{ if .readme }}
				<table class="wide">
					<thead>
						<tr class="title-row">
							<th>{{ .readme_filename }}</th>
						</tr>
					</thead>
					<tbody>
						<tr>
							<td id="readme">
								{{ .readme -}}
							</td>
						</tr>
					</tbody>
				</table>
			{{ end }}
		</div>
		<footer>
			{{ template "footer" . }}
		</footer>
	</body>
</html>
{{- end -}}
{{- define "repo_tree_file" -}}
<!DOCTYPE html>
<html lang="en">
	<head>
		{{ template "head_common" . }}
		<link rel="stylesheet" href="/:/static/chroma.css" />
		<title>{{ .group_name }}/repos/{{ .repo_name }}/{{ .path_spec }} &ndash; Lindenii Forge</title>
	</head>
	<body class="repo-tree-file">
		<header>
			{{ template "header" . }}
		</header>
		<header>
			{{ template "repo_header" . }}
		</header>
		<p>
			/{{ .path_spec }} (<a href="/{{ .group_name }}/:/repos/{{ .repo_name }}/raw/{{ .path_spec }}{{ if not (eq .ref_type "head") }}?{{ .ref_type }}={{ .ref }}{{ end }}">raw</a>)
		</p>
		{{ .file_contents }}
		<footer>
			{{ template "footer" . }}
		</footer>
	</body>
</html>
{{- end -}}