blob: ce822917050962dbba268dfbce861ec0e2913629 [file] [log] [blame]
Giorgi Lekveishvili52814d92023-06-15 19:30:32 +04001package main
2
3import (
giob36178f2024-08-23 18:59:15 +04004 "errors"
Giorgi Lekveishvili52814d92023-06-15 19:30:32 +04005 "fmt"
6 "os/exec"
Giorgi Lekveishvili027ef432023-06-16 12:31:25 +04007 "strings"
Giorgi Lekveishvili52814d92023-06-15 19:30:32 +04008)
9
giob36178f2024-08-23 18:59:15 +040010var ErrorAlreadyExists = errors.New("already exists")
11
Giorgi Lekveishvili52814d92023-06-15 19:30:32 +040012type client struct {
13 config string
14}
15
16func newClient(config string) *client {
17 return &client{
18 config: fmt.Sprintf("--config=%s", config),
19 }
20}
21
22func (c *client) createUser(name string) error {
23 cmd := exec.Command("headscale", c.config, "users", "create", name)
24 out, err := cmd.Output()
giob36178f2024-08-23 18:59:15 +040025 outStr := string(out)
26 if err != nil && strings.Contains(outStr, "User already exists") {
27 return ErrorAlreadyExists
28 }
Giorgi Lekveishvili52814d92023-06-15 19:30:32 +040029 return err
30}
31
32func (c *client) createPreAuthKey(user string) (string, error) {
33 // TODO(giolekva): make expiration configurable, and auto-refresh
34 cmd := exec.Command("headscale", c.config, "--user", user, "preauthkeys", "create", "--reusable", "--expiration", "365d")
35 out, err := cmd.Output()
Giorgi Lekveishvili027ef432023-06-16 12:31:25 +040036 if err != nil {
37 return "", err
38 }
Giorgi Lekveishvili52814d92023-06-15 19:30:32 +040039 fmt.Println(string(out))
Giorgi Lekveishvili027ef432023-06-16 12:31:25 +040040 return extractLastLine(string(out))
Giorgi Lekveishvili52814d92023-06-15 19:30:32 +040041}
42
43func (c *client) enableRoute(id string) error {
44 // TODO(giolekva): make expiration configurable, and auto-refresh
45 cmd := exec.Command("headscale", c.config, "routes", "enable", "-r", id)
46 out, err := cmd.Output()
47 fmt.Println(string(out))
48 return err
49}
Giorgi Lekveishvili027ef432023-06-16 12:31:25 +040050
51func extractLastLine(s string) (string, error) {
52 items := strings.Split(s, "\n")
53 for i := len(items) - 1; i >= 0; i-- {
54 t := strings.TrimSpace(items[i])
55 if t != "" {
56 return t, nil
57 }
58 }
59 return "", fmt.Errorf("All lines are empty")
60}