package main

import (
	"github.com/labstack/echo"
	"html/template"
	"io"
	"net/http"
)

const BaseUrl = `https://git.kolaente.de/vikunja`
const Domain = `code.vikunja.io`
const GoGetTemplate = `<!doctype html>
<html>
	<head>
		<meta name="go-import" content="` + Domain + `{{.}} git ` + BaseUrl + `{{.}}.git">
		<meta name="go-source" content="` + Domain + `{{.}} _ ` + BaseUrl + `{{.}}/src/branch/master{/dir} ` + BaseUrl + `{{.}}/src/branch/master{/dir}/{file}#L{line}">
		<meta http-equiv="refresh" content="0; url=` + BaseUrl + `{{.}}" />
	</head>
	<body>
		go get ` + Domain + `{{.}}
	</body>
</html>
`

type Template struct {
	templates *template.Template
}

func (t *Template) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
	return t.templates.ExecuteTemplate(w, name, data)
}

func redirectToBase(c echo.Context) error {
	return c.Redirect(http.StatusFound, BaseUrl+c.Request().URL.String())
}

func showGoGetMeta(c echo.Context) error {
	switch c.Param("repo") {
	case "goget":
		return c.Render(http.StatusOK, "goget", c.Request().URL.Path)
	case "web":
		return c.Render(http.StatusOK, "goget", c.Request().URL.Path)
	case "api":
		return c.Render(http.StatusOK, "goget", c.Request().URL.Path)
	default:
		return redirectToBase(c)
	}
}

func main() {
	e := echo.New()
	renderer := &Template{
		templates: template.Must(template.New("goget").Parse(GoGetTemplate)),
	}
	e.Renderer = renderer

	e.GET("/*", redirectToBase)
	e.GET("/:repo", showGoGetMeta)
	e.Logger.Fatal(e.Start(":8080"))
}
