| Giorgi Lekveishvili | 52814d9 | 2023-06-15 19:30:32 +0400 | [diff] [blame] | 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "os/exec" |
| Giorgi Lekveishvili | 027ef43 | 2023-06-16 12:31:25 +0400 | [diff] [blame^] | 6 | "strings" |
| Giorgi Lekveishvili | 52814d9 | 2023-06-15 19:30:32 +0400 | [diff] [blame] | 7 | ) |
| 8 | |
| 9 | type client struct { |
| 10 | config string |
| 11 | } |
| 12 | |
| 13 | func newClient(config string) *client { |
| 14 | return &client{ |
| 15 | config: fmt.Sprintf("--config=%s", config), |
| 16 | } |
| 17 | } |
| 18 | |
| 19 | func (c *client) createUser(name string) error { |
| 20 | cmd := exec.Command("headscale", c.config, "users", "create", name) |
| 21 | out, err := cmd.Output() |
| 22 | fmt.Println(string(out)) |
| 23 | return err |
| 24 | } |
| 25 | |
| 26 | func (c *client) createPreAuthKey(user string) (string, error) { |
| 27 | // TODO(giolekva): make expiration configurable, and auto-refresh |
| 28 | cmd := exec.Command("headscale", c.config, "--user", user, "preauthkeys", "create", "--reusable", "--expiration", "365d") |
| 29 | out, err := cmd.Output() |
| Giorgi Lekveishvili | 027ef43 | 2023-06-16 12:31:25 +0400 | [diff] [blame^] | 30 | if err != nil { |
| 31 | return "", err |
| 32 | } |
| Giorgi Lekveishvili | 52814d9 | 2023-06-15 19:30:32 +0400 | [diff] [blame] | 33 | fmt.Println(string(out)) |
| Giorgi Lekveishvili | 027ef43 | 2023-06-16 12:31:25 +0400 | [diff] [blame^] | 34 | return extractLastLine(string(out)) |
| Giorgi Lekveishvili | 52814d9 | 2023-06-15 19:30:32 +0400 | [diff] [blame] | 35 | } |
| 36 | |
| 37 | func (c *client) enableRoute(id string) error { |
| 38 | // TODO(giolekva): make expiration configurable, and auto-refresh |
| 39 | cmd := exec.Command("headscale", c.config, "routes", "enable", "-r", id) |
| 40 | out, err := cmd.Output() |
| 41 | fmt.Println(string(out)) |
| 42 | return err |
| 43 | } |
| Giorgi Lekveishvili | 027ef43 | 2023-06-16 12:31:25 +0400 | [diff] [blame^] | 44 | |
| 45 | func extractLastLine(s string) (string, error) { |
| 46 | items := strings.Split(s, "\n") |
| 47 | for i := len(items) - 1; i >= 0; i-- { |
| 48 | t := strings.TrimSpace(items[i]) |
| 49 | if t != "" { |
| 50 | return t, nil |
| 51 | } |
| 52 | } |
| 53 | return "", fmt.Errorf("All lines are empty") |
| 54 | } |