package main

import (
	"log"
	"net/http"
	"os"
	"path/filepath"
	"strings"
)

const (
	defaultPort = "80"
	webRoot     = "/www"
	indexName   = "index.html"
)

func main() {
	port := strings.TrimSpace(os.Getenv("PORT"))
	if port == "" {
		port = defaultPort
	}

	server := &http.Server{
		Addr:    ":" + port,
		Handler: http.HandlerFunc(serve),
	}

	log.Printf("dist server listening on :%s", port)
	if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
		log.Fatal(err)
	}
}

func serve(w http.ResponseWriter, r *http.Request) {
	requestPath := strings.TrimPrefix(filepath.Clean("/"+r.URL.Path), "/")
	if requestPath == "." || requestPath == "" {
		serveIndex(w, r)
		return
	}

	fullPath := filepath.Join(webRoot, filepath.FromSlash(requestPath))
	if info, err := os.Stat(fullPath); err == nil && !info.IsDir() {
		applyAssetCacheHeaders(w, requestPath)
		http.ServeFile(w, r, fullPath)
		return
	}

	serveIndex(w, r)
}

func serveIndex(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Cache-Control", "no-cache")
	w.Header().Set("Pragma", "no-cache")
	w.Header().Set("Expires", "0")
	http.ServeFile(w, r, filepath.Join(webRoot, indexName))
}

func applyAssetCacheHeaders(w http.ResponseWriter, requestPath string) {
	if strings.EqualFold(requestPath, indexName) {
		w.Header().Set("Cache-Control", "no-cache")
		w.Header().Set("Pragma", "no-cache")
		w.Header().Set("Expires", "0")
		return
	}

	if strings.HasPrefix(requestPath, "static/") {
		w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
	}
}
