-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
94 lines (81 loc) · 2.32 KB
/
Copy pathmain.go
File metadata and controls
94 lines (81 loc) · 2.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package main
import (
"context"
"crypto/rand"
"encoding/hex"
"errors"
"net"
"os"
"os/signal"
"syscall"
"time"
tea "charm.land/bubbletea/v2"
"charm.land/log/v2"
"charm.land/wish/v2"
"charm.land/wish/v2/activeterm"
"charm.land/wish/v2/bubbletea"
"charm.land/wish/v2/logging"
"github.com/charmbracelet/ssh"
"github.com/rasjonell/chessh/internal/app"
"github.com/rasjonell/chessh/internal/multiplayer"
)
const (
defaultHost = "localhost"
defaultPort = "23234"
defaultHostKeyPath = ".ssh/id_ed25519"
)
func main() {
manager := multiplayer.NewManager()
host := envOrDefault("CHESSH_HOST", defaultHost)
port := envOrDefault("CHESSH_PORT", defaultPort)
hostKeyPath := envOrDefault("CHESSH_HOST_KEY_PATH", defaultHostKeyPath)
address := net.JoinHostPort(host, port)
s, err := wish.NewServer(
wish.WithAddress(address),
wish.WithHostKeyPath(hostKeyPath),
wish.WithMiddleware(
bubbletea.Middleware(func(s ssh.Session) (tea.Model, []tea.ProgramOption) {
return teaHandler(s, manager)
}),
activeterm.Middleware(),
logging.Middleware(),
),
)
if err != nil {
log.Error("Could not start server", "error", err)
}
done := make(chan os.Signal, 1)
signal.Notify(done, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
log.Info("Starting SSH server", "address", address, "host_key_path", hostKeyPath)
go func() {
if err = s.ListenAndServe(); err != nil && !errors.Is(err, ssh.ErrServerClosed) {
log.Error("Could not start server", "error", err)
done <- nil
}
}()
<-done
log.Info("Stopping SSH server")
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err := s.Shutdown(ctx); err != nil && !errors.Is(err, ssh.ErrServerClosed) {
log.Error("Could not stop server", "error", err)
}
}
func teaHandler(s ssh.Session, manager *multiplayer.Manager) (tea.Model, []tea.ProgramOption) {
pty, _, _ := s.Pty()
m := app.NewModel(pty.Term, pty.Window.Width, pty.Window.Height, manager, sessionID(), s.Context().Done())
return m, []tea.ProgramOption{}
}
func sessionID() string {
buf := make([]byte, 8)
if _, err := rand.Read(buf); err != nil {
return time.Now().Format("150405.000000000")
}
return hex.EncodeToString(buf)
}
func envOrDefault(key, fallback string) string {
if value := os.Getenv(key); value != "" {
return value
}
return fallback
}