1package main
  2
  3import (
  4	"context"
  5	"fmt"
  6	"os"
  7	"os/signal"
  8	"path/filepath"
  9	"syscall"
 10	"time"
 11
 12	"github.com/charmbracelet/soft-serve/server"
 13	"github.com/charmbracelet/soft-serve/server/backend"
 14	"github.com/charmbracelet/soft-serve/server/config"
 15	"github.com/charmbracelet/soft-serve/server/db"
 16	"github.com/charmbracelet/soft-serve/server/db/migrate"
 17	"github.com/charmbracelet/soft-serve/server/hooks"
 18	"github.com/spf13/cobra"
 19)
 20
 21var (
 22	syncHooks bool
 23
 24	serveCmd = &cobra.Command{
 25		Use:                "serve",
 26		Short:              "Start the server",
 27		Args:               cobra.NoArgs,
 28		PersistentPreRunE:  initBackendContext,
 29		PersistentPostRunE: closeDBContext,
 30		RunE: func(cmd *cobra.Command, _ []string) error {
 31			ctx := cmd.Context()
 32			cfg := config.DefaultConfig()
 33			if cfg.Exist() {
 34				if err := cfg.ParseFile(); err != nil {
 35					return fmt.Errorf("parse config file: %w", err)
 36				}
 37			} else {
 38				if err := cfg.WriteConfig(); err != nil {
 39					return fmt.Errorf("write config file: %w", err)
 40				}
 41			}
 42
 43			if err := cfg.ParseEnv(); err != nil {
 44				return fmt.Errorf("parse environment variables: %w", err)
 45			}
 46
 47			// Create custom hooks directory if it doesn't exist
 48			customHooksPath := filepath.Join(cfg.DataPath, "hooks")
 49			if _, err := os.Stat(customHooksPath); err != nil && os.IsNotExist(err) {
 50				os.MkdirAll(customHooksPath, os.ModePerm) // nolint: errcheck
 51				// Generate update hook example without executable permissions
 52				hookPath := filepath.Join(customHooksPath, "update.sample")
 53				// nolint: gosec
 54				if err := os.WriteFile(hookPath, []byte(updateHookExample), 0o744); err != nil {
 55					return fmt.Errorf("failed to generate update hook example: %w", err)
 56				}
 57			}
 58
 59			// Create log directory if it doesn't exist
 60			logPath := filepath.Join(cfg.DataPath, "log")
 61			if _, err := os.Stat(logPath); err != nil && os.IsNotExist(err) {
 62				os.MkdirAll(logPath, os.ModePerm) // nolint: errcheck
 63			}
 64
 65			db := db.FromContext(ctx)
 66			if err := migrate.Migrate(ctx, db); err != nil {
 67				return fmt.Errorf("migration error: %w", err)
 68			}
 69
 70			s, err := server.NewServer(ctx)
 71			if err != nil {
 72				return fmt.Errorf("start server: %w", err)
 73			}
 74
 75			if syncHooks {
 76				be := backend.FromContext(ctx)
 77				if err := initializeHooks(ctx, cfg, be); err != nil {
 78					return fmt.Errorf("initialize hooks: %w", err)
 79				}
 80			}
 81
 82			done := make(chan os.Signal, 1)
 83			lch := make(chan error, 1)
 84			go func() {
 85				defer close(lch)
 86				defer close(done)
 87				lch <- s.Start()
 88			}()
 89
 90			signal.Notify(done, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
 91			<-done
 92
 93			ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
 94			defer cancel()
 95			if err := s.Shutdown(ctx); err != nil {
 96				return err
 97			}
 98
 99			// wait for serve to finish
100			return <-lch
101		},
102	}
103)
104
105func init() {
106	serveCmd.Flags().BoolVarP(&syncHooks, "sync-hooks", "", false, "synchronize hooks for all repositories before running the server")
107}
108
109func initializeHooks(ctx context.Context, cfg *config.Config, be *backend.Backend) error {
110	repos, err := be.Repositories(ctx)
111	if err != nil {
112		return err
113	}
114
115	for _, repo := range repos {
116		if err := hooks.GenerateHooks(ctx, cfg, repo.Name()); err != nil {
117			return err
118		}
119	}
120
121	return nil
122}