1package tui
2
3import (
4 "encoding/json"
5 "fmt"
6 "log"
7 "soft-serve/git"
8 "time"
9
10 tea "github.com/charmbracelet/bubbletea"
11 "github.com/gliderlabs/ssh"
12)
13
14func SessionHandler(reposPath string, repoPoll time.Duration) func(ssh.Session) (tea.Model, []tea.ProgramOption) {
15 rs := git.NewRepoSource(reposPath)
16 err := createDefaultConfigRepo(rs)
17 if err != nil {
18 if err != nil {
19 log.Fatalf("cannot create config repo: %s", err)
20 }
21 }
22 appCfg, err := loadConfig(rs)
23 if err != nil {
24 if err != nil {
25 log.Printf("cannot load config: %s", err)
26 }
27 }
28 go func() {
29 for {
30 time.Sleep(repoPoll)
31 ct := time.Now()
32 err := rs.LoadRepos()
33 if err != nil {
34 log.Printf("cannot load repos: %s", err)
35 continue
36 }
37 cfg, err := loadConfig(rs)
38 if err != nil {
39 if err != nil {
40 log.Printf("cannot load config: %s", err)
41 continue
42 }
43 }
44 log.Printf("Repos loaded in %s", time.Since(ct))
45 appCfg = cfg
46 }
47 }()
48
49 return func(s ssh.Session) (tea.Model, []tea.ProgramOption) {
50 cmd := s.Command()
51 cfg := &SessionConfig{}
52 switch len(cmd) {
53 case 0:
54 cfg.InitialRepo = ""
55 case 1:
56 cfg.InitialRepo = cmd[0]
57 default:
58 return nil, nil
59 }
60 pty, _, active := s.Pty()
61 if !active {
62 fmt.Println("not active")
63 return nil, nil
64 }
65 cfg.Width = pty.Window.Width
66 cfg.Height = pty.Window.Height
67 return NewBubble(appCfg, cfg), []tea.ProgramOption{tea.WithAltScreen()}
68 }
69}
70
71func loadConfig(rs *git.RepoSource) (*Config, error) {
72 cfg := &Config{}
73 cfg.RepoSource = rs
74 cr, err := rs.GetRepo("config")
75 if err != nil {
76 return nil, fmt.Errorf("cannot load config repo: %s", err)
77 }
78 cs, err := cr.LatestFile("config.json")
79 if err != nil {
80 return nil, fmt.Errorf("cannot load config.json: %s", err)
81 }
82 err = json.Unmarshal([]byte(cs), cfg)
83 if err != nil {
84 return nil, fmt.Errorf("bad json in config.json: %s", err)
85 }
86 return cfg, nil
87}