// Package server is de webinterface, de git-HTTP-server en de API.
package server

import (
	"context"
	"crypto/rand"
	"embed"
	"encoding/hex"
	"fmt"
	"html/template"
	"io/fs"
	"log/slog"
	"net/http"
	"net/url"
	"strings"
	"sync"
	"time"
	"unicode/utf8"

	"gitlab.com/Timfa/bluegit/internal/access"
	"gitlab.com/Timfa/bluegit/internal/activity"
	"gitlab.com/Timfa/bluegit/internal/auth"
	"gitlab.com/Timfa/bluegit/internal/card"
	"gitlab.com/Timfa/bluegit/internal/cispec"
	"gitlab.com/Timfa/bluegit/internal/config"
	"gitlab.com/Timfa/bluegit/internal/i18n"
	"gitlab.com/Timfa/bluegit/internal/realip"
	"gitlab.com/Timfa/bluegit/internal/runner"
	"gitlab.com/Timfa/bluegit/internal/store"
)

//go:embed templates/*.html static/*
var webFS embed.FS

// Server bedient BlueGit.
type Server struct {
	Cfg     config.Config
	Store   *store.Store
	Auth    auth.Provider
	Mail    auth.Mailer
	Dev     bool
	Git     string
	HookBin string
	Runner  *runner.Runner
	Log     *slog.Logger
	// hookSink vangt de JSON-body af in tests, vóór het HTTP-verzoek.
	hookSink func([]byte)
	// StateDir is de map met database en het bestand storage_path.
	StateDir string
	// AfterStorage krijgt het nieuwe datadisk-pad, voor runner en SSH.
	AfterStorage func(path string)
	// UpdateStarter start bluegit-update.service. Nil gebruikt systemctl.
	UpdateStarter UpdateStarter
	updateHits    updateLimiter
	tmpl          *template.Template
	byLang        map[string]*template.Template

	storageMu  sync.RWMutex
	storage    string
	storageSet bool
	usageMu    sync.Mutex
	usage      dirUsage
	cards      *card.Cache
	// mergingMR zijn merge requests die opMergeMR nu zelf afrondt.
	// AfterPush mag hun bronbranch niet alvast verwijderen.
	mergingMR sync.Map
}

type principal struct {
	User    store.User
	Session store.Session
	OK      bool
}

type ctxKey struct{}

// Handler is de HTTP-handler met sessies en koppen.
func (s *Server) Handler() http.Handler {
	s.mustTemplates()
	mux := http.NewServeMux()
	mux.HandleFunc("GET /assets/{file}", s.asset)
	mux.HandleFunc("GET /-/info", s.infoPage)
	mux.HandleFunc("GET /-/card.png", s.cardPNG)
	mux.HandleFunc("GET /api/v1/oembed", s.oembed)
	s.mountAPI(mux)
	mux.HandleFunc("GET /api/v1/admin/self-update", s.selfUpdateStatus)
	mux.HandleFunc("POST /api/v1/admin/self-update", s.selfUpdate)
	mux.HandleFunc("GET /api/v1/webhooks/openapi.json", s.webhookSpec)
	mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
		_, _ = w.Write([]byte("ok\n"))
	})
	mux.HandleFunc("GET /login", s.login)
	mux.HandleFunc("GET /auth/callback", s.callback)
	mux.HandleFunc("POST /logout", s.logout)
	mux.HandleFunc("GET /{$}", s.home)
	mux.HandleFunc("GET /new", s.newPage)
	mux.HandleFunc("GET /new/slug", s.slugPreview)
	mux.HandleFunc("POST /new/repo", s.createRepo)
	mux.HandleFunc("POST /new/group", s.createGroup)
	mux.HandleFunc("GET /setup", s.setupPage)
	mux.HandleFunc("POST /setup", s.setupSave)
	mux.HandleFunc("GET /settings", s.account)
	mux.HandleFunc("POST /settings/language", s.saveLanguage)
	mux.HandleFunc("POST /settings/profile", s.saveProfile)
	mux.HandleFunc("POST /settings/tokens", s.createToken)
	mux.HandleFunc("POST /settings/tokens/delete", s.deleteToken)
	mux.HandleFunc("POST /settings/ssh", s.addSSH)
	mux.HandleFunc("POST /settings/ssh/delete", s.deleteSSH)
	mux.HandleFunc("GET /settings/export", s.export)
	mux.HandleFunc("GET /users/{username}", s.profile)
	mux.HandleFunc("GET /{name}", s.userShort)
	mux.HandleFunc("GET /groups/{path}", s.groupPage)
	mux.HandleFunc("GET /groups/{path}/logo", s.groupLogo)
	mux.HandleFunc("POST /groups/{path}/settings", s.saveGroup)
	mux.HandleFunc("POST /groups/{path}/approvals", s.saveGroupApproval)
	mux.HandleFunc("POST /groups/{path}/owner", s.transferGroup)
	mux.HandleFunc("POST /groups/{path}/logo", s.uploadGroupLogo)
	mux.HandleFunc("POST /groups/{path}/members", s.groupMember)
	mux.HandleFunc("POST /groups/{path}/members/remove", s.groupMemberRemove)
	mux.HandleFunc("POST /groups/{path}/secrets", s.groupSecret)
	mux.HandleFunc("POST /groups/{path}/secrets/reveal", s.groupSecretReveal)
	mux.HandleFunc("POST /groups/{path}/secrets/delete", s.groupSecretDelete)
	mux.HandleFunc("POST /groups/{path}/webhooks", s.groupWebhook)
	mux.HandleFunc("POST /groups/{path}/webhooks/delete", s.groupWebhookDelete)

	mux.HandleFunc("GET /{owner}/{repo}/info/refs", s.gitHTTP)
	mux.HandleFunc("POST /{owner}/{repo}/git-upload-pack", s.gitHTTP)
	mux.HandleFunc("POST /{owner}/{repo}/git-receive-pack", s.gitHTTP)
	mux.HandleFunc("POST /api/v1/repos/{owner}/{repo}/releases", s.createRelease)
	mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/jobs/{id}/log", s.jobLogAPI)
	mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/commits/{sha}/diff", s.commitDiffAPI)
	mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/merge-requests/{number}/diff", s.mrDiffAPI)
	mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/issues", s.issuesAPI)
	mux.HandleFunc("POST /api/v1/repos/{owner}/{repo}/issues", s.issuesAPI)
	mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/issues/{number}", s.issueAPI)
	mux.HandleFunc("PUT /api/v1/repos/{owner}/{repo}/issues/{number}", s.issueAPI)
	mux.HandleFunc("DELETE /api/v1/repos/{owner}/{repo}/issues/{number}", s.issueAPI)
	mux.HandleFunc("POST /api/v1/repos/{owner}/{repo}/issues/{number}/notes", s.issueNoteAPI)
	mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/labels", s.labelsAPI)
	mux.HandleFunc("POST /api/v1/repos/{owner}/{repo}/labels", s.labelsAPI)
	mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/milestones", s.milestonesAPI)
	mux.HandleFunc("POST /api/v1/repos/{owner}/{repo}/milestones", s.milestonesAPI)
	mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/webhook-secrets", s.repoWebhookSecrets)
	mux.HandleFunc("POST /api/v1/repos/{owner}/{repo}/webhooks", s.repoWebhookAPI)
	mux.HandleFunc("PUT /api/v1/repos/{owner}/{repo}/webhooks/{id}", s.repoWebhookUpdate)
	mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/secrets", s.repoSecretsAPI)
	mux.HandleFunc("POST /api/v1/repos/{owner}/{repo}/secrets", s.repoSecretCreateAPI)
	mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/secrets/{name}", s.repoSecretRevealAPI)
	mux.HandleFunc("PUT /api/v1/repos/{owner}/{repo}/secrets/{name}", s.repoSecretUpdateAPI)
	mux.HandleFunc("POST /api/v1/repos/{owner}/{repo}/secrets/{name}/replace", s.repoSecretReplaceAPI)
	mux.HandleFunc("DELETE /api/v1/repos/{owner}/{repo}/secrets/{name}", s.repoSecretDeleteAPI)
	mux.HandleFunc("GET /api/v1/groups/{path}/webhook-secrets", s.groupWebhookSecrets)
	mux.HandleFunc("POST /api/v1/groups/{path}/hooks", s.groupWebhookAPI)
	mux.HandleFunc("PUT /api/v1/groups/{path}/hooks/{id}", s.groupWebhookUpdate)
	mux.HandleFunc("GET /api/v1/groups/{path}/secrets", s.groupSecretsAPI)
	mux.HandleFunc("POST /api/v1/groups/{path}/secrets", s.groupSecretCreateAPI)
	mux.HandleFunc("GET /api/v1/groups/{path}/secrets/{name}", s.groupSecretRevealAPI)
	mux.HandleFunc("PUT /api/v1/groups/{path}/secrets/{name}", s.groupSecretUpdateAPI)
	mux.HandleFunc("POST /api/v1/groups/{path}/secrets/{name}/replace", s.groupSecretReplaceAPI)
	mux.HandleFunc("DELETE /api/v1/groups/{path}/secrets/{name}", s.groupSecretDeleteAPI)
	mux.HandleFunc("GET /{owner}/{repo}", s.repoHome)
	mux.HandleFunc("GET /{owner}/{repo}/-/tree", s.treeRoot)
	mux.HandleFunc("GET /{owner}/{repo}/-/tree/{path...}", s.tree)
	mux.HandleFunc("GET /{owner}/{repo}/-/blob/{path...}", s.blob)
	mux.HandleFunc("GET /{owner}/{repo}/-/commits", s.commits)
	mux.HandleFunc("GET /{owner}/{repo}/-/tags", s.tags)
	mux.HandleFunc("POST /{owner}/{repo}/-/tags", s.createTag)
	mux.HandleFunc("POST /{owner}/{repo}/-/tags/delete", s.deleteTag)
	mux.HandleFunc("GET /{owner}/{repo}/-/tags/archive", s.tagArchive)
	mux.HandleFunc("GET /{owner}/{repo}/-/archive/{rev}/{file}", s.commitArchive)
	mux.HandleFunc("GET /{owner}/{repo}/-/commit/{sha}", s.commit)
	mux.HandleFunc("GET /{owner}/{repo}/-/branches/archive", s.branchArchive)
	mux.HandleFunc("GET /{owner}/{repo}/-/branches", s.branches)
	mux.HandleFunc("POST /{owner}/{repo}/-/branches", s.createBranch)
	mux.HandleFunc("POST /{owner}/{repo}/-/branches/delete", s.deleteBranch)
	mux.HandleFunc("POST /{owner}/{repo}/-/branches/rename", s.renameBranch)
	mux.HandleFunc("GET /{owner}/{repo}/-/compare", s.compare)
	mux.HandleFunc("POST /{owner}/{repo}/-/markdown", s.previewMarkdown)
	mux.HandleFunc("POST /{owner}/{repo}/-/tasks", s.toggleTask)
	mux.HandleFunc("GET /{owner}/{repo}/-/merge-requests", s.mergeRequests)
	mux.HandleFunc("GET /{owner}/{repo}/-/merge-requests/new", s.newMR)
	mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests", s.createMR)
	mux.HandleFunc("GET /{owner}/{repo}/-/merge-requests/{number}", s.showMR)
	mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}", s.updateMR)
	mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/merge", s.mergeMR)
	mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/close", s.closeMR)
	mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/reopen", s.reopenMR)
	mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/reviews", s.postReview)
	mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/reviews/dismiss", s.dismissReview)
	mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/notes", s.createNote)
	mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/suggestions", s.applySuggestions)
	mux.HandleFunc("GET /{owner}/{repo}/-/issues", s.issuesPage)
	mux.HandleFunc("GET /{owner}/{repo}/-/issues/new", s.newIssue)
	mux.HandleFunc("POST /{owner}/{repo}/-/issues", s.createIssue)
	mux.HandleFunc("POST /{owner}/{repo}/-/issues/labels", s.createIssueLabel)
	mux.HandleFunc("POST /{owner}/{repo}/-/issues/milestones", s.createIssueMilestone)
	mux.HandleFunc("GET /{owner}/{repo}/-/issues/{number}", s.showIssue)
	mux.HandleFunc("POST /{owner}/{repo}/-/issues/{number}", s.postIssue)
	mux.HandleFunc("GET /{owner}/{repo}/-/pipelines", s.pipelines)
	mux.HandleFunc("POST /{owner}/{repo}/-/pipelines", s.runPipeline)
	mux.HandleFunc("GET /{owner}/{repo}/-/pipelines/{id}", s.pipeline)
	mux.HandleFunc("GET /{owner}/{repo}/-/pipelines/{id}/jobs/{job}", s.showJob)
	mux.HandleFunc("GET /{owner}/{repo}/-/pipelines/{id}/jobs/{job}/log", s.jobLog)
	mux.HandleFunc("POST /{owner}/{repo}/-/pipelines/{id}/jobs/{job}/play", s.playJob)
	mux.HandleFunc("POST /{owner}/{repo}/-/pipelines/{id}/retry", s.retryPipeline)
	mux.HandleFunc("GET /{owner}/{repo}/-/ci/editor", s.ciEditor)
	mux.HandleFunc("POST /{owner}/{repo}/-/ci/editor", s.saveCIEditor)
	mux.HandleFunc("POST /{owner}/{repo}/-/ci/lint", s.lintCI)
	mux.HandleFunc("GET /{owner}/{repo}/-/releases", s.releases)
	mux.HandleFunc("GET /{owner}/{repo}/-/releases/{tag}/assets/{name}", s.releaseAsset)
	mux.HandleFunc("GET /{owner}/{repo}/-/logo", s.repoLogo)
	mux.HandleFunc("POST /{owner}/{repo}/-/logo", s.uploadRepoLogo)
	mux.HandleFunc("POST /{owner}/{repo}/-/star", s.toggleStar)
	mux.HandleFunc("GET /{owner}/{repo}/-/settings", s.settings)
	mux.HandleFunc("POST /{owner}/{repo}/-/settings", s.updateRepo)
	mux.HandleFunc("POST /{owner}/{repo}/-/approvals", s.saveRepoApproval)
	mux.HandleFunc("POST /{owner}/{repo}/-/members", s.repoMember)
	mux.HandleFunc("POST /{owner}/{repo}/-/members/remove", s.repoMemberRemove)
	mux.HandleFunc("POST /{owner}/{repo}/-/protected", s.addProtected)
	mux.HandleFunc("POST /{owner}/{repo}/-/protected/remove", s.removeProtected)
	mux.HandleFunc("POST /{owner}/{repo}/-/protected-tags", s.addProtectedTag)
	mux.HandleFunc("POST /{owner}/{repo}/-/protected-tags/remove", s.removeProtectedTag)
	mux.HandleFunc("POST /{owner}/{repo}/-/secrets", s.repoSecret)
	mux.HandleFunc("POST /{owner}/{repo}/-/secrets/reveal", s.repoSecretReveal)
	mux.HandleFunc("POST /{owner}/{repo}/-/secrets/delete", s.repoSecretDelete)
	mux.HandleFunc("POST /{owner}/{repo}/-/webhooks", s.repoWebhook)
	mux.HandleFunc("POST /{owner}/{repo}/-/webhooks/delete", s.repoWebhookDelete)
	mux.HandleFunc("POST /{owner}/{repo}/-/delete", s.deleteRepo)

	return s.realIP(s.withSession(s.secure(s.gate(mux))))
}

func (s *Server) realIP(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		realip.Apply(r, s.Cfg.ProxySet())
		next.ServeHTTP(w, r)
	})
}

func (s *Server) mustTemplates() {
	if s.byLang != nil {
		return
	}
	s.byLang = map[string]*template.Template{}
	for _, lang := range i18n.All() {
		l := lang
		s.byLang[string(l)] = template.Must(template.New("web").Funcs(template.FuncMap{
			"short": func(v string) string {
				if len(v) > 10 {
					return v[:10]
				}
				return v
			},
			"join": strings.Join,
			"initial": func(s string) string {
				s = strings.TrimSpace(s)
				if s == "" {
					return "?"
				}
				r, _ := utf8.DecodeRuneInString(s)
				return strings.ToUpper(string(r))
			},
			"tileHue": tileHue,
			"splitPath": func(p string) []string {
				if p == "" {
					return nil
				}
				return strings.Split(p, "/")
			},
			"iconOf": func(name string) string { return fileIcon(name, "blob") },
			"t":      func(key string, args ...any) string { return i18n.T(l, key, args...) },
			"date":   func(t time.Time) string { return i18n.FormatDate(l, t) },
			"tn": func(n int, one, many string) string {
				key := many
				if n == 1 {
					key = one
				}
				return i18n.T(l, key, n)
			},
			"roleName": func(r access.Role) string { return i18n.T(l, "role."+string(r)) },
			"visName":  func(v string) string { return i18n.T(l, "vis."+v) },
			"presetName": func(id string) string {
				label := i18n.T(l, "set.preset."+id)
				if label == "set.preset."+id {
					return id
				}
				return label
			},
			"printf": fmt.Sprintf,
			"dict": func(kv ...any) (map[string]any, error) {
				if len(kv)%2 != 0 {
					return nil, fmt.Errorf("dict")
				}
				m := make(map[string]any, len(kv)/2)
				for i := 0; i < len(kv); i += 2 {
					key, ok := kv[i].(string)
					if !ok {
						return nil, fmt.Errorf("dict")
					}
					m[key] = kv[i+1]
				}
				return m, nil
			},
		}).ParseFS(webFS, "templates/*.html"))
	}
	s.tmpl = s.byLang[string(i18n.EN)]
}

func (s *Server) asset(w http.ResponseWriter, r *http.Request) {
	name := r.PathValue("file")
	if name == "" || strings.Contains(name, "/") || strings.Contains(name, "..") {
		http.NotFound(w, r)
		return
	}
	sub, err := fs.Sub(webFS, "static")
	if err != nil {
		http.Error(w, "assets", http.StatusInternalServerError)
		return
	}
	http.ServeFileFS(w, r, sub, name)
}

func (s *Server) secure(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("X-Content-Type-Options", "nosniff")
		w.Header().Set("X-Frame-Options", "DENY")
		w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin")
		w.Header().Set("Content-Security-Policy", "default-src 'self'; img-src 'self' https://auth.timfalken.com data:; style-src 'self'; form-action 'self'; base-uri 'self'; frame-ancestors 'none'")
		next.ServeHTTP(w, r)
	})
}

func (s *Server) withSession(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		p := principal{}
		if c, err := r.Cookie("bluegit_session"); err == nil && c.Value != "" {
			sess, err := s.Store.Session(r.Context(), c.Value)
			if err == nil && sess.ExpiresAt.After(time.Now()) {
				p.Session = sess
				p.User = sess.User
				p.OK = true
				s.maybeExtend(r.Context(), sess)
			}
		}
		next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), ctxKey{}, p)))
	})
}

func (s *Server) maybeExtend(ctx context.Context, sess store.Session) {
	if time.Until(sess.ExpiresAt) > 6*time.Hour {
		return
	}
	sec, err := s.Auth.Extend(ctx, sess.AccessToken)
	if err != nil || sec <= 0 {
		return
	}
	_ = s.Store.UpdateSessionExpiry(ctx, sess.ID, time.Now().Add(time.Duration(sec)*time.Second))
}

func (s *Server) who(r *http.Request) principal {
	p, _ := r.Context().Value(ctxKey{}).(principal)
	return p
}

func (s *Server) csrfOK(w http.ResponseWriter, r *http.Request) bool {
	if err := r.ParseForm(); err != nil {
		http.Error(w, s.tr(r, "err.badForm"), http.StatusBadRequest)
		return false
	}
	p := s.who(r)
	if !p.OK || r.FormValue("csrf") == "" || r.FormValue("csrf") != p.Session.CSRF {
		http.Error(w, s.tr(r, "err.badCSRF"), http.StatusBadRequest)
		return false
	}
	return true
}

func (s *Server) loginRequired(w http.ResponseWriter, r *http.Request) (store.User, bool) {
	p := s.who(r)
	if !p.OK {
		http.Redirect(w, r, "/login", http.StatusFound)
		return store.User{}, false
	}
	return p.User, true
}

func (s *Server) setSessionCookie(w http.ResponseWriter, id string, exp time.Time) {
	http.SetCookie(w, &http.Cookie{
		Name:     "bluegit_session",
		Value:    id,
		Path:     "/",
		HttpOnly: true,
		SameSite: http.SameSiteLaxMode,
		Secure:   strings.HasPrefix(s.Cfg.BaseURL, "https://"),
		Expires:  exp,
	})
}

func (s *Server) flash(w http.ResponseWriter, notice, problem string) {
	secure := strings.HasPrefix(s.Cfg.BaseURL, "https://")
	if notice != "" {
		http.SetCookie(w, &http.Cookie{Name: "bluegit_notice", Value: url.QueryEscape(notice), Path: "/", MaxAge: 120, HttpOnly: true, Secure: secure, SameSite: http.SameSiteLaxMode})
	}
	if problem != "" {
		http.SetCookie(w, &http.Cookie{Name: "bluegit_error", Value: url.QueryEscape(problem), Path: "/", MaxAge: 120, HttpOnly: true, Secure: secure, SameSite: http.SameSiteLaxMode})
	}
}

func (s *Server) takeFlash(w http.ResponseWriter, r *http.Request) (string, string) {
	notice, problem := flashVal(r, "bluegit_notice"), flashVal(r, "bluegit_error")
	if notice != "" {
		http.SetCookie(w, &http.Cookie{Name: "bluegit_notice", Value: "", Path: "/", MaxAge: -1})
	}
	if problem != "" {
		http.SetCookie(w, &http.Cookie{Name: "bluegit_error", Value: "", Path: "/", MaxAge: -1})
	}
	return notice, problem
}

func cookieVal(r *http.Request, name string) string {
	c, err := r.Cookie(name)
	if err != nil {
		return ""
	}
	return c.Value
}

func flashVal(r *http.Request, name string) string {
	raw := cookieVal(r, name)
	if raw == "" {
		return ""
	}
	v, err := url.QueryUnescape(raw)
	if err != nil {
		return raw
	}
	return v
}

func (s *Server) redirect(w http.ResponseWriter, r *http.Request, path, notice, problem string) {
	s.flash(w, notice, problem)
	http.Redirect(w, r, path, http.StatusSeeOther)
}

func (s *Server) langOf(r *http.Request) i18n.Lang {
	if p := s.who(r); p.OK {
		return i18n.Parse(p.User.Language)
	}
	return i18n.EN
}

func (s *Server) tr(r *http.Request, key string, args ...any) string {
	return i18n.T(s.langOf(r), key, args...)
}

func (s *Server) trErr(r *http.Request, err error) string {
	return i18n.Text(s.langOf(r), err)
}

func (s *Server) view(w http.ResponseWriter, r *http.Request, title string) View {
	notice, problem := s.takeFlash(w, r)
	lang := s.langOf(r)
	if strings.HasPrefix(title, "title.") {
		title = i18n.T(lang, title)
	}
	name := strings.TrimSpace(s.Cfg.Runner.Name)
	if name == "" {
		name = "Steve"
	}
	v := View{
		Title: title, BaseURL: s.Cfg.BaseURL, RunnerName: name, Notice: notice, Err: problem,
		StorageUnset: s.StoragePath() == "", Lang: string(lang), HTMLLang: htmlLang(lang),
		Cunei: lang == i18n.Cuneiform,
	}
	for _, l := range i18n.All() {
		v.Langs = append(v.Langs, LangChoice{Code: string(l), Label: l.Name()})
	}
	if p := s.who(r); p.OK && !isCrawler(r) {
		u := p.User
		v.User = &u
		v.CSRF = p.Session.CSRF
	}
	pic := s.cardForPath(r.Context(), r.URL.Path, r.URL.RawQuery, r.URL.Fragment)
	v.Social = &pic.Meta
	return v
}

func htmlLang(l i18n.Lang) string {
	switch l {
	case i18n.NL:
		return "nl"
	case i18n.DE:
		return "de"
	case i18n.FR:
		return "fr"
	default:
		return "en"
	}
}

func (s *Server) render(w http.ResponseWriter, name string, v View) {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	tmpl := s.byLang[v.Lang]
	if tmpl == nil {
		tmpl = s.tmpl
	}
	if err := tmpl.ExecuteTemplate(w, name, v); err != nil && s.Log != nil {
		s.Log.Error("sjabloon", "name", name, "err", err)
	}
}

func randomState() (string, error) {
	b := make([]byte, 32)
	if _, err := rand.Read(b); err != nil {
		return "", err
	}
	return hex.EncodeToString(b), nil
}

// View is de gegevensset voor elk scherm.
type View struct {
	Title          string
	BaseURL        string
	RunnerName     string
	User           *store.User
	CSRF           string
	Notice         string
	Err            string
	Repos          []store.Repo
	Groups         []store.Group
	Repo           *store.Repo
	Role           access.Role
	CanWrite       bool
	CanAdmin       bool
	CanMerge       bool
	CanForce       bool
	CanComment     bool
	CanApply       bool
	Commits        []CommitRow
	CommitDays     []CommitDay
	CommitPrev     string
	CommitNext     string
	Commit         *CommitRow
	CommitDiff     *CommitDiff
	Entries        []EntryRow
	TreePath       string
	Blob           string
	BlobPath       string
	Binary         bool
	Branches       []BranchRow
	Branch         *BranchBoard
	MRs            []store.MergeRequest
	Flow           *FlowBoard
	MR             *store.MergeRequest
	Banner         *MRBanner
	MRPipe         *PipeRow
	MergeBlocks    []string
	Approval       *ApprovalView
	Reviews        []ReviewRow
	CanReview      bool
	CanApprove     bool
	CanDismiss     bool
	CanClose       bool
	CanReopen      bool
	IsOwner        bool
	Candidates     []store.Member
	Diff           string
	DiffFiles      []DiffFileView
	Pipes          []store.Pipeline
	PipeRows       []PipeRow
	Pipe           *store.Pipeline
	PipeSource     string
	PipeStatus     string
	PipeLabel      string
	PipeJobs       []JobLink
	PipeStages     []StageView
	PipeFailed     bool
	Live           bool
	LiveURL        string
	Jobs           []store.Job
	JobPage        *JobPage
	Editor         *CIEditor
	Releases       []store.Release
	Members        []store.Member
	Secrets        []store.SecretMeta
	HookSecrets    []SecretChoice
	Hooks          []HookView
	HookEdit       HookDraft
	Patterns       []string
	TagPatterns    []string
	Tags           []TagRow
	Tokens         []store.TokenInfo
	ShowExpiry     bool
	Keys           []store.SSHKey
	CloneHTTP      string
	CloneSSH       string
	Group          *store.Group
	Tab            string
	Rev            string
	NewToken       string
	StorageUnset   bool
	StoragePath    string
	StorageFree    string
	StorageUsed    string
	StorageTotal   string
	StoragePercent int
	StorageBlueGit string
	StoragePartial bool
	MinFree        string
	Wide           bool
	Info           bool
	ShowUpdate     bool
	Update         *UpdateView
	HookDoc        string
	Spec           cispec.Doc
	SpecJSON       template.JS
	APIJSON        template.JS
	Page           string
	Lang           string
	HTMLLang       string
	Cunei          bool
	Langs          []LangChoice
	Query          string
	SortDir        string
	FlipDir        string
	Cards          []RepoCard
	Head           *CommitRow
	Files          []FileRow
	Tree           []FileRow
	Readme         template.HTML
	ReadmeName     string
	LicensePath    string
	NCommits       int
	NBranches      int
	NTags          int
	NReleases      int
	Created        string
	Lines          []CodeLine
	BlobSize       string
	FileName       string
	RevProtected   bool
	Heat           *activity.Calendar
	Notes          []NoteRow
	Profile        *store.User
	Card           *ProfileCard
	DescHTML       template.HTML
	Timeline       []TimelineItem
	CompareFrom    string
	CompareTo      string
	FormTitle      string
	Labels         []string
	CanEditMR      bool
	Issues         *IssueBoard
	IssueDoc       string
	DescTpls       []string
	TplPick        string
	FormBody       string
	Social         *card.Meta
}

// LangChoice is één taal in de instellingen.
type LangChoice struct {
	Code, Label string
}

// RepoCard is een repository in een groepslijst.
type RepoCard struct {
	Repo    store.Repo
	Stars   int
	Starred bool
	When    string
}

// AccountLink is een naam die naar een profiel wijst.
type AccountLink struct {
	Name string
	URL  string
}

// ProfileCard is het blok over een gebruiker, boven de activiteitenkalender.
type ProfileCard struct {
	User                   store.User
	Name, Since, Bio, URL  string
	Heading                string
	Repos, Groups, Contrib int
	Own                    bool
}

// NoteRow is een reactie in de interface.
type NoteRow struct {
	ID                                  int64
	Author, AuthorURL, Body, When, Path string
	Start, End                          int
	HasSuggestion                       bool
	ParentID                            int64
	HTML                                template.HTML
	Replies                             []NoteRow
	At                                  time.Time
}

// DiffFileView is één bestand in de merge-request-diff.
type DiffFileView struct {
	Path  string
	Lines []DiffLineView
}

// DiffLineView is één diffregel, met de reacties die op het nieuwe regelnummer eindigen.
type DiffLineView struct {
	Kind  string
	Text  string
	Old   int
	New   int
	Notes []NoteRow
}

// TagRow is één tag op de tagspagina.
type TagRow struct {
	Name, Message, SHA, Short, Subject, Date, When string
	Annotated, Protected, HasRelease, CanDelete    bool
	ZipURL, TarURL                                 string
}

// FileRow is een rij in de bestandstabel of de boom.
type FileRow struct {
	Name, Path, Icon, Subject, When, SHA string
	Dir                                  bool
	Depth                                int
	Active                               bool
	// Open geldt voor een map die het huidige pad bevat. De browser
	// onthoudt afwijkingen daarvan per repository.
	Open bool
}

// CodeLine is één regel broncode.
type CodeLine struct {
	N    int
	HTML template.HTML
}

// CommitRow is een commit in de interface.
// Author is de gekoppelde gebruiker, of anders de ruwe git-naam.
// RawName en PushedBy zijn gezet als de pusher de fallback is en de git-naam afwijkt.
type CommitRow struct {
	SHA, Short, Author, Who, Date, Subject, Body, When  string
	UserURL, WhoURL, Avatar, Initial, RawName, PushedBy string
	Ident                                               template.HTML
	PipeID                                              int64
	PipeStatus, PipeLabel, PipeDuration                 string
	PipeStages                                          []StageView
	PipeLive, PipeFailed                                bool
}

// CommitDay is één dag op de commitlijst, nieuwste dag eerst.
type CommitDay struct {
	Label string
	Items []CommitRow
}

// EntryRow is een bestand of map.
type EntryRow struct {
	Name, Type, Path string
}

// BranchRow is een branch, met of zonder bescherming.
type BranchRow struct {
	Name, SHA, Short, Subject, When, WhenTitle string
	RepoPath, ZipURL, TarURL                   string
	Protected, Default, CanEdit                bool
	Target                                     string
	Ahead, Behind                              int
	Unix                                       int64
	PipeID                                     int64
	PipeStatus, PipeLabel                      string
	OpenMRs                                    []int64
}

// BranchBoard is de gegroepeerde branches-pagina.
type BranchBoard struct {
	State                 string
	ShowActive, ShowStale bool
	Active, Stale         []BranchRow
}

// TimelineItem is één gebeurtenis of reactie op een merge request.
type TimelineItem struct {
	ID                    int64
	Kind                  string
	Actor, ActorURL, Text string
	When                  string
	Body                  string
	HTML                  template.HTML
	URL                   string
	Replies               []TimelineItem
	At                    time.Time
	Rank                  int
}

// HookView is een webhook plus de laatste pogingen.
type HookView struct {
	ID         int64
	Name       string
	Preset     string
	URL        string
	Method     string
	Filter     string
	Events     string
	Badges     []string
	Deliveries []store.Delivery
}

// HookDraft vult het webhookformulier bij bewerken. ID 0 is een nieuw formulier.
type HookDraft struct {
	ID       int64
	Name     string
	Preset   string
	Filter   string
	URL      string
	Username string
	Avatar   string
	Icon     string
	Alias    string
	Token    string
	Chat     string
	Server   string
	Topic    string
	Home     string
	Room     string
	Method   string
	CType    string
	Headers  string
	Body     string
	OnPush   bool
	OnMR     bool
	OnOK     bool
	OnFail   bool
	OnRel    bool
	OnIssue  bool
}

func repoURL(repo store.Repo) string { return "/" + repo.FullPath() }
