package main

import (
	"errors"
	"fmt"
	"os"
	"os/user"

	"git.tilde.town/tildetown/town/request"
	townUser "git.tilde.town/tildetown/town/user"
)

func _main(args []string) error {
	currentUser, err := user.Current()
	if err != nil {
		return err
	}

	ok, err := townUser.IsAdmin(currentUser)
	if err != nil {
		return err
	}
	if !ok {
		return errors.New("must be a town admin")
	}

	errs := []error{}

	err = request.ProcessGitea(request.RequestPath)
	if err != nil {
		errs = append(errs, err)
	}

	err = request.ProcessGemini(request.RequestPath)
	if err != nil {
		errs = append(errs, err)
	}

	if len(errs) > 0 {
		errMsg := "errors encountered during request processing: "
		for _, e := range errs {
			errMsg += e.Error() + " "
		}
		return fmt.Errorf("errors encountered during request processing: %s", errMsg)
	}

	return nil
}

func main() {
	retcode := 0

	err := _main(os.Args)
	if err != nil {
		fmt.Fprintln(os.Stderr, err.Error())
		retcode = 1
	}

	os.Exit(retcode)
}
