summaryrefslogtreecommitdiff
path: root/cli/main.go
blob: d0b21658923ec61a20723133c24e37c28b02d80f (plain)
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
package main

import (
	"flag"
	"fmt"
	"log"
	"os"
	"os/exec"
	"strings"

	eduvpn "github.com/jwijenbergh/eduvpn-common/src"
)

func openBrowser(urlString string) {
	log.Printf("OAuth: Initialized with AuthURL %s\n", urlString)
	log.Println("OAuth: Opening browser with xdg-open...")
	exec.Command("xdg-open", urlString).Start()
}

func logState(oldState string, newState string, data string) {
	log.Printf("State: %s -> State: %s with data %s\n", oldState, newState, data)

	if newState == "SERVER_OAUTH_STARTED" {
		openBrowser(data)
	}
}

func getGraphviz(fsm *eduvpn.FSM, graph string) string {
	if fsm == nil {
		return graph
	}

	for name, state := range fsm.States {
		for _, transition := range state.Transition {
			graph += "\n" + "cluster_" + name.String() + "-> cluster_" + transition.String()
		}

		graph += "\nsubgraph cluster_" + name.String() + "{\n"
		if (state.Locked) {
			graph += "bgcolor=\"red\"\n"
		}
		if (fsm.Current == name) {
			graph += "color=\"blue\"\n"
		} else {
			graph += "color=\"\"\n"
		}
		graph += "label=" + name.String()
		graph = getGraphviz(state.Sub, graph)
		graph += "\n}"
	}
	return graph
}

func generateGraph() string {
	state := eduvpn.GetVPNState()

	state.InitializeFSM()


	graph := "digraph fsm {\n"
	graph += "nodesep=2"
	graph = getGraphviz(state.FSM, graph)
	graph += "\n}"

	return graph
}

func main() {
	generateGraph()
	fileGraph := flag.String("dumpgraph", "", "Dump the FSM to a graphviz fdp file")
	urlArg := flag.String("url", "", "The url of the vpn")
	flag.Parse()

	fileGraphString := *fileGraph
	if fileGraphString != "" {
		f, err := os.Create(fileGraphString)

		if err != nil {
			log.Fatalf("Failed to create file %s with error %v", fileGraphString, err)
		}

		defer f.Close()

		f.WriteString(generateGraph())

		log.Printf("Graph written to file: %s, use 'fdp %s -Tsvg > graph.svg' from graphviz to save to a svg file called graph.svg\n", fileGraphString, fileGraphString)
		return
	}
	urlString := *urlArg

	if urlString != "" {
		if !strings.HasPrefix(urlString, "https://") {
			urlString = "https://" + urlString
		}

		state := eduvpn.GetVPNState()

		state.Register("org.eduvpn.app.linux", "configs", logState)
		config, configErr := state.Connect(urlString)

		if configErr != nil {
			fmt.Printf("Config error %v", configErr)
			return
		}

		log.Println(config)

		return
	}

	flag.PrintDefaults()
}