5
5
"os"
6
6
"os/exec"
7
7
"runtime"
8
+ "strings"
8
9
9
10
"github.com/pterm/pterm"
10
11
"github.com/twirapp/twir/cli/internal/shell"
@@ -20,34 +21,49 @@ var Cmd = &cli.Command{
20
21
return err
21
22
}
22
23
24
+ caddyFindCmd := exec .Command (
25
+ "go" ,
26
+ "tool" ,
27
+ "-n" , // -n prints the command without running it, giving us the path
28
+ "github.com/caddyserver/caddy/v2/cmd/caddy" ,
29
+ )
30
+ caddyFindCmd .Dir = wd
31
+ caddyPathBytes , err := caddyFindCmd .Output ()
32
+ if err != nil {
33
+ return fmt .Errorf ("failed to find Caddy path: %v" , err )
34
+ }
35
+ caddyPath := strings .TrimSpace (string (caddyPathBytes ))
36
+
23
37
if runtime .GOOS == "linux" {
24
- caddyFindCmd := exec .Command (
25
- "go" ,
26
- "tool" ,
27
- "-n" ,
28
- "github.com/caddyserver/caddy/v2/cmd/caddy" ,
29
- )
30
- caddyFindCmd .Dir = wd
31
- caddyFindCmdOutPut , err := caddyFindCmd .Output ()
38
+ // Check if the capability is already set
39
+ getcapCmd := exec .Command ("getcap" , caddyPath )
40
+ getcapCmd .Dir = wd
41
+ getcapOutput , err := getcapCmd .Output ()
32
42
if err != nil {
33
- return err
43
+ // If getcap fails (e.g., command not found), proceed cautiously
44
+ pterm .Warning .Println ("Could not check capabilities; assuming they need to be set" )
34
45
}
35
46
36
- pterm .Warning .Println ("!!! ATTENTION !!!" )
37
- pterm .Info .Println ("We need your sudo password to bind web server to port 443" )
38
-
39
- if err := shell .ExecCommand (
40
- shell.ExecCommandOpts {
41
- Command : fmt .Sprintf (
42
- `sudo setcap 'cap_net_bind_service=+ep' %s` ,
43
- string (caddyFindCmdOutPut ),
44
- ),
45
- Stdout : os .Stdout ,
46
- Stderr : os .Stderr ,
47
- Pwd : wd ,
48
- },
49
- ); err != nil {
50
- return err
47
+ // Check if cap_net_bind_service is present
48
+ if ! strings .Contains (string (getcapOutput ), "cap_net_bind_service" ) {
49
+ pterm .Warning .Println ("!!! ATTENTION !!!" )
50
+ pterm .Warning .Println ("We need your sudo password to bind web server to port 443 (this is a one-time setup)" )
51
+
52
+ // Set the capability if missing
53
+ setcapCmd := fmt .Sprintf ("sudo setcap 'cap_net_bind_service=+ep' %s" , caddyPath )
54
+ if err := shell .ExecCommand (
55
+ shell.ExecCommandOpts {
56
+ Command : setcapCmd ,
57
+ Stdout : os .Stdout ,
58
+ Stderr : os .Stderr ,
59
+ Pwd : wd ,
60
+ },
61
+ ); err != nil {
62
+ return fmt .Errorf ("failed to set capability: %v" , err )
63
+ }
64
+ pterm .Success .Println ("Capability set successfully; no further sudo prompts needed unless Caddy binary changes" )
65
+ } else {
66
+ pterm .Info .Println ("Caddy already has permission to bind to port 443; no sudo required" )
51
67
}
52
68
}
53
69
0 commit comments