package main

import (
	"fmt"
	"os"

	"go.alanpearce.eu/website/internal/builder"
	"go.alanpearce.eu/website/internal/config"
	"go.alanpearce.eu/x/log"

	"github.com/ardanlabs/conf/v3"
	"gitlab.com/tozd/go/errors"
)

func main() {
	ioConfig := &builder.IOConfig{}
	if help, err := conf.Parse("", ioConfig); err != nil {
		if errors.Is(err, conf.ErrHelpWanted) {
			fmt.Println(help)
			os.Exit(1)
		}
		panic("error parsing configuration: " + err.Error())
	}
	log := log.Configure(!ioConfig.Development)

	log.Debug("starting build process")
	if ioConfig.Source != "." {
		err := os.Chdir(ioConfig.Source)
		if err != nil {
			log.Panic("could not change to source directory")
		}
	}
	cfg, err := config.GetConfig(ioConfig.Source, log)
	if err != nil {
		log.Error("could not read config", "error", err)
	}

	_, err = builder.BuildSite(ioConfig, cfg, log)
	if err != nil {
		log.Error("could not build site", "error", err)
		os.Exit(1)
	}
}