-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
113 lines (96 loc) · 2.02 KB
/
main.go
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package main
import (
_ "embed"
"fmt"
"io"
"log"
"os"
"os/exec"
"os/user"
"path"
)
//go:embed init.zsh
var initZSH []byte
func usage() {
fmt.Printf("usage %s: kacpersh [init zsh]", os.Args[0])
os.Exit(1)
}
func main() {
// TODO: replace with actual argument parsing
if len(os.Args) > 1 {
if os.Args[1] == "init" {
if len(os.Args) != 3 {
usage()
}
switch os.Args[2] {
case "zsh":
os.Stdout.Write(initZSH)
default:
fmt.Printf("shell \"%s\" is not supported\n", os.Args[2])
usage()
}
} else {
usage()
}
os.Exit(0)
}
if path, ok := os.LookupEnv("KACPERSH_DEBUG"); ok {
f, err := os.Create(path)
if err != nil {
panic(err)
}
defer f.Close()
log.SetOutput(f)
} else {
log.SetOutput(io.Discard)
}
outCh := make(chan []byte)
outByteCh := make(chan byte)
go func() {
for buf := range outCh {
os.Stdout.Write(buf)
for _, ch := range buf {
outByteCh <- ch
}
}
}()
recorder := NewRecorder(outByteCh, 32*1024*1024)
go recorder.Run()
tempDir, err := createTempDir()
if err != nil {
log.Fatalf("creating a temp dir: %s", err)
}
defer os.RemoveAll(tempDir)
socketPath := path.Join(tempDir, "control")
control := ControlServer{SocketPath: socketPath, Recorder: recorder}
go func() {
if err := control.ListenAndServe(); err != nil {
log.Fatalf("control server: %s", err)
}
}()
os.Setenv("KACPERSH_SOCK", socketPath)
shell := os.Getenv("SHELL")
if len(shell) == 0 {
log.Fatalf("Please set the SHELL variable to a supported shell.")
}
term := Term{
Command: exec.Command(shell, "-l"),
BufSize: 1, // has to be 1 until we implement in-band signaling
}
if err := term.Spawn(outCh); err != nil {
log.Fatalf("%s", err)
}
}
func createTempDir() (string, error) {
username := "unknown"
currentUser, err := user.Current()
if err == nil {
username = currentUser.Username
}
tempDirPattern := fmt.Sprintf("kacpersh-%s-*", username)
tempDir, err := os.MkdirTemp("", tempDirPattern)
if err != nil {
return "", err
}
return tempDir, nil
}