package main

import (
	"bufio"
	_ "embed"
	"flag"
	"fmt"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"strings"
	"text/template"
)

//go:embed hjem.html
var hjemTemplate string

var port = flag.Int("p", 1437, "set the port for hjem to use")

type HjemData struct {
	OS    string
	Email string
}

func main() {
	flag.Parse()

	t, err := template.New("hjem").Parse(hjemTemplate)
	if err != nil {
		panic(err)
	}

	user_os := "Unknown"

	file, err := os.Open("/etc/os-release")
	if err != nil {
		panic(err)
	}
	defer file.Close()

	scanner := bufio.NewScanner(file)
	if scanner.Scan() {
		user_os = strings.TrimRight(strings.TrimLeft(scanner.Text(), "NAME='"), "'")
	}

	user_email := "unknown@example.com"

	file, err = os.Open(filepath.Join(func() string {
		hostname, err := os.UserHomeDir()
		if err != nil {
			panic(err)
		}
		return hostname
	}(), ".gitconfig"))
	if err != nil {
		panic(err)
	}
	defer file.Close()

	scanner = bufio.NewScanner(file)
	for scanner.Scan() {
		text := scanner.Text()
		if strings.Contains(text, "email = ") {
			user_email = strings.TrimLeft(strings.TrimSpace(text), "email = ")
			break
		}
	}

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "text/html; charset=utf-8")

		err := t.ExecuteTemplate(w, "hjem", HjemData{
			OS:    user_os,
			Email: user_email,
		})
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
	})

	fmt.Printf("Web server is available at http://0.0.0.0:%d\n", *port)
	fmt.Println("Press Ctrl+C to stop")

	log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", *port), nil))
}
