cerrado @ ada6a68b4f25c912705542a6b03aae7ffffb5e99

  1package main
  2
  3import (
  4	"context"
  5	"crypto/rand"
  6	"encoding/base64"
  7	"flag"
  8	"fmt"
  9	"log/slog"
 10	"os"
 11	"os/signal"
 12	"time"
 13
 14	"github.com/alecthomas/chroma/v2/styles"
 15	"golang.org/x/crypto/bcrypt"
 16
 17	"git.gabrielgio.me/cerrado/pkg/config"
 18	"git.gabrielgio.me/cerrado/pkg/handler"
 19	"git.gabrielgio.me/cerrado/pkg/service"
 20	"git.gabrielgio.me/cerrado/pkg/worker"
 21)
 22
 23func main() {
 24	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, os.Kill)
 25	defer stop()
 26
 27	if len(os.Args) == 4 && os.Args[1] == "hash" {
 28		err := hash(os.Args[2], os.Args[3])
 29		if err != nil {
 30			slog.Error("Hash", "error", err)
 31			os.Exit(1)
 32		}
 33		return
 34	}
 35
 36	if len(os.Args) == 2 && os.Args[1] == "key" {
 37		err := key()
 38		if err != nil {
 39			slog.Error("Key", "error", err)
 40			os.Exit(1)
 41		}
 42		return
 43	}
 44
 45	if err := run(ctx); err != nil {
 46		slog.Error("Server", "error", err)
 47		os.Exit(1)
 48	}
 49}
 50
 51func hash(username string, password string) error {
 52	passphrase := fmt.Sprintf("%s:%s", username, password)
 53	bytes, err := bcrypt.GenerateFromPassword([]byte(passphrase), 14)
 54	if err != nil {
 55		return err
 56	}
 57	fmt.Println(string(bytes))
 58	return nil
 59}
 60
 61func key() error {
 62	key := make([]byte, 64)
 63
 64	_, err := rand.Read(key)
 65	if err != nil {
 66		return err
 67	}
 68
 69	en := base64.StdEncoding.EncodeToString(key)
 70	fmt.Println(en)
 71	return nil
 72}
 73
 74func run(ctx context.Context) error {
 75	configPath := flag.String("config", "/etc/cerrado.scfg", "File path for the configuration file")
 76
 77	flag.Parse()
 78
 79	// repositorie
 80	configRepo, err := config.LoadConfigurationRepository(*configPath)
 81	if err != nil {
 82		return err
 83	}
 84
 85	// checking chroma configurationo
 86
 87	if _, ok := styles.Registry[configRepo.GetSyntaxHighlight()]; !ok {
 88		slog.Warn(
 89			"Invalid Syntax highlight selected",
 90			"invalid-style", configRepo.GetSyntaxHighlight(),
 91			"using", "monokailight",
 92		)
 93		styles.Fallback = styles.Registry["monokailight"]
 94	}
 95
 96	// services
 97	gitService := service.NewGitService(configRepo)
 98
 99	handler, err := handler.MountHandler(gitService, configRepo)
100	if err != nil {
101		return err
102	}
103
104	serverTask := worker.NewServerTask(configRepo.GetListenAddr(), handler)
105
106	pool := worker.NewTaskPool()
107	pool.AddTask("http-server", 5*time.Second, serverTask)
108
109	return pool.Start(ctx)
110}