package main

import (
	"fmt"
	"log"
	"net/http"
	"os"

	"git.schreifuchs.ch/schreifuchs/ng-blog/internal/config"
	"git.schreifuchs.ch/schreifuchs/ng-blog/internal/initialize"

	"go-simpler.org/env"
)

const HELP = "expected 'serve' or 'help' subcommands"

var ENV_OPTS = &env.Options{NameSep: "_"}

func main() {
	if len(os.Args) < 2 {
		fmt.Println(HELP)
		return
	}
	switch os.Args[1] {
	case "serve":
		serve()
	case "help":
		help()
	default:
		fmt.Println(HELP)
		os.Exit(1)
	}
}

func serve() {
	cfg := config.Default()

	if err := env.Load(cfg, ENV_OPTS); err != nil {
		log.Fatal(err)
	}
	log.Println("config loaded")

	mux := initialize.CreateMux(cfg)
	if err := http.ListenAndServe(fmt.Sprintf(":%d", cfg.Port), mux); err != nil {
		log.Fatal(err)
	}
}

func help() {
	env.Usage(config.Default(), os.Stdout, ENV_OPTS)
	os.Exit(0)
}
