package mark2web

import (
	"io/ioutil"
	"regexp"
	"strings"

	"gitbase.de/apairon/mark2web/pkg/logger"
)

func htaccessRedirect(outDir, goTo string) {
	switch Config.Webserver.Type {
	case "apache":
		htaccessFile := outDir + "/.htaccess"
		logger.N("writing '%s' with redirect to: %s", htaccessFile, goTo)
		err := ioutil.WriteFile(htaccessFile, []byte(`RewriteEngine on
RewriteRule ^$ %{REQUEST_URI}`+goTo+`/ [R,L]
`), 0644)
		logger.Eexit(err, "could not write '%s'", htaccessFile)
	}
}

// WriteWebserverConfig build the config for pre compression and more
func (tree *TreeNode) WriteWebserverConfig() {
	goTo := ""
	if g := tree.Config.This.GoTo; g != nil && *g != "" {
		goTo = strings.TrimPrefix(*g, "/")
	}

	switch Config.Webserver.Type {
	case "apache":
		configStr := `
RewriteEngine on

`

		if goTo != "" {
			configStr += `
RewriteRule ^$ %{REQUEST_URI}` + goTo + `/ [R,L]

`
		}

		configStr += `
AddCharset UTF-8 .html
AddCharset UTF-8 .json
AddCharset UTF-8 .js
AddCharset UTF-8 .css

RemoveLanguage .br

<IfModule mod_headers.c>
`

		rewriteMacro := func(e, c, x, xx string) string {
			return `

    ######` + e + `.` + x + `

    RewriteCond "%{HTTP:Accept-encoding}" "` + xx + `"
    RewriteCond "%{REQUEST_FILENAME}\.` + x + `" -s
    RewriteRule "^(.*)` + e + `" "$1` + e + `\.` + x + `" [QSA]

    RewriteRule "` + e + `\.` + x + `$" "-" [E=no-gzip:1,E=no-brotli]

    <FilesMatch "` + e + `\.` + x + `$">
      ForceType '` + c + `; charset=UTF-8'
      Header append Content-Encoding ` + xx + `
      Header append Vary Accept-Encoding
    </FilesMatch>

`
		}

		for ext, contentType := range Config.Compress.Extensions {
			rExt := regexp.QuoteMeta(ext)
			if brotliSupported && Config.Compress.Brotli {
				configStr += rewriteMacro(rExt, contentType, "br", "br")
			}
			if Config.Compress.GZIP {
				configStr += rewriteMacro(rExt, contentType, "gz", "gzip")
			}
		}

		configStr += `
</IfModule>
`

		if configStr != "" {
			htaccessFile := Config.Directories.Output + "/.htaccess"
			logger.N("writing webserver config to: %s", htaccessFile)
			err := ioutil.WriteFile(htaccessFile, []byte(configStr), 0644)
			logger.Eexit(err, "could not write '%s'", htaccessFile)
		}
	}
}
