| Giorgi Lekveishvili | 52814d9 | 2023-06-15 19:30:32 +0400 | [diff] [blame] | 1 | package main |
| 2 | |
| 3 | import ( |
| gio | b36178f | 2024-08-23 18:59:15 +0400 | [diff] [blame] | 4 | "errors" |
| Giorgi Lekveishvili | 52814d9 | 2023-06-15 19:30:32 +0400 | [diff] [blame] | 5 | "fmt" |
| 6 | "os/exec" |
| Giorgi Lekveishvili | 027ef43 | 2023-06-16 12:31:25 +0400 | [diff] [blame] | 7 | "strings" |
| Giorgi Lekveishvili | 52814d9 | 2023-06-15 19:30:32 +0400 | [diff] [blame] | 8 | ) |
| 9 | |
| gio | b36178f | 2024-08-23 18:59:15 +0400 | [diff] [blame] | 10 | var ErrorAlreadyExists = errors.New("already exists") |
| 11 | |
| Giorgi Lekveishvili | 52814d9 | 2023-06-15 19:30:32 +0400 | [diff] [blame] | 12 | type client struct { |
| 13 | config string |
| 14 | } |
| 15 | |
| 16 | func newClient(config string) *client { |
| 17 | return &client{ |
| 18 | config: fmt.Sprintf("--config=%s", config), |
| 19 | } |
| 20 | } |
| 21 | |
| 22 | func (c *client) createUser(name string) error { |
| 23 | cmd := exec.Command("headscale", c.config, "users", "create", name) |
| 24 | out, err := cmd.Output() |
| gio | b36178f | 2024-08-23 18:59:15 +0400 | [diff] [blame] | 25 | outStr := string(out) |
| 26 | if err != nil && strings.Contains(outStr, "User already exists") { |
| 27 | return ErrorAlreadyExists |
| 28 | } |
| Giorgi Lekveishvili | 52814d9 | 2023-06-15 19:30:32 +0400 | [diff] [blame] | 29 | return err |
| 30 | } |
| 31 | |
| 32 | func (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 Lekveishvili | 027ef43 | 2023-06-16 12:31:25 +0400 | [diff] [blame] | 36 | if err != nil { |
| 37 | return "", err |
| 38 | } |
| Giorgi Lekveishvili | 52814d9 | 2023-06-15 19:30:32 +0400 | [diff] [blame] | 39 | fmt.Println(string(out)) |
| Giorgi Lekveishvili | 027ef43 | 2023-06-16 12:31:25 +0400 | [diff] [blame] | 40 | return extractLastLine(string(out)) |
| Giorgi Lekveishvili | 52814d9 | 2023-06-15 19:30:32 +0400 | [diff] [blame] | 41 | } |
| 42 | |
| 43 | func (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 Lekveishvili | 027ef43 | 2023-06-16 12:31:25 +0400 | [diff] [blame] | 50 | |
| 51 | func 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 | } |