package main

import (
	"flag"
	"fmt"
	"os"

	"gopkg.in/yaml.v2"
)

type (
	Config struct {
		Cert    Cert
		Port    int
		Domains map[string]map[string]Endpoint
	}

	Cert struct {
		CRT string
		Key string
	}

	Endpoint struct {
		To        string
		Redir     bool
		BasicAuth string
	}
)

func NewConfig() (Config, error) {
	var c Config

	fs := flag.NewFlagSet(os.Args[0], flag.ContinueOnError)
	fs.StringVar(&c.Cert.CRT, "crt", "", "path to .crt")
	fs.StringVar(&c.Cert.Key, "key", "", "path to .key")
	fs.IntVar(&c.Port, "p", 56112, "port to listen on")
	f := fs.String("f", "/dev/null", `file of {domain:{"":{"": {to:"", basicAuth:""}}}}`)
	if err := fs.Parse(os.Args[1:]); err != nil {
		return c, err
	}

	if b, err := os.ReadFile(*f); err != nil {
		return c, err
	} else if err := yaml.Unmarshal(b, &c); err != nil {
		return c, err
	} else if len(c.Domains) == 0 {
		return c, fmt.Errorf("no domains configured")
	}

	return c, nil
}
