Initial code

Bug: misc:36

Change-Id: I659ce2684ec02960ffa2bdf1636aeccd44f3010e
diff --git a/sip_reverter.go b/sip_reverter.go
new file mode 100644
index 0000000..3cfcb16
--- /dev/null
+++ b/sip_reverter.go
@@ -0,0 +1,134 @@
+package main
+
+import (
+	"errors"
+	"fmt"
+	"log"
+	"net/url"
+	"os"
+	"regexp"
+	"strconv"
+	"time"
+
+	hguclient "gomodules.avm99963.com/hgu-sipsettings-reverter/client"
+)
+
+var (
+	obProxyAddrRe = regexp.MustCompile(`oa0 = "([\d\.]*)";`)
+	obProxyPortRe = regexp.MustCompile(`op0 = "(\d*)";`)
+	ipInterfaceRe = regexp.MustCompile(`var ifn = '([^']*)';`)
+)
+
+type OutboundProxySettings struct {
+	Address     string
+	Port        int
+	IpInterface string
+}
+
+func GetOutboundProxySettings(client *hguclient.Client) (*OutboundProxySettings, error) {
+	loggedIn, err := client.IsLoggedIn()
+	if err != nil {
+		return nil, err
+	}
+	if !loggedIn {
+		log.Println("Not logged in, logging in...")
+		err := client.LogIn()
+		if err != nil {
+			return nil, err
+		}
+	}
+	body, err := client.Get(hguclient.URL_SIPBASIC, false)
+	if err != nil {
+		return nil, err
+	}
+	addrMatches := obProxyAddrRe.FindStringSubmatch(body)
+	if len(addrMatches) < 2 {
+		return nil, errors.New("Can't find outbound proxy address in settings.")
+	}
+	addr := addrMatches[1]
+	portMatches := obProxyPortRe.FindStringSubmatch(body)
+	if len(portMatches) < 2 {
+		return nil, errors.New("Can't find oubound proxy port in settings.")
+	}
+	port, err := strconv.Atoi(portMatches[1])
+	if err != nil {
+		return nil, err
+	}
+	ipMatches := ipInterfaceRe.FindStringSubmatch(body)
+	if len(ipMatches) < 2 {
+		return nil, errors.New("Can't find IP interface in settings.")
+	}
+	ip := ipMatches[1]
+	return &OutboundProxySettings{
+		Address:     addr,
+		Port:        port,
+		IpInterface: ip,
+	}, nil
+}
+
+func check(client *hguclient.Client, correctSettings *OutboundProxySettings) error {
+	currentSettings, err := GetOutboundProxySettings(client)
+	if err != nil {
+		log.Fatalln(err)
+	}
+	if *currentSettings == *correctSettings {
+    log.Println("Settings are ok.")
+		return nil
+	}
+	log.Println(fmt.Sprintf("Settings are incorrect! Current settings: %v. Correct settings: %v.", currentSettings, correctSettings))
+	_, err = client.Get("/voicesipstop.cmd", false)
+	if err != nil {
+		return errors.New(fmt.Sprintf("Couldn't stop SIP: %v", err))
+	}
+	eAddr := url.QueryEscape(correctSettings.Address)
+	ePort := url.QueryEscape(strconv.Itoa(correctSettings.Port))
+	eInt := url.QueryEscape(correctSettings.IpInterface)
+	startUrl := "/voicesipstart.cmd?currentview=basic&ifName=" + eInt + "&obProxyAddr0=" + eAddr + "&obProxyPort0=" + ePort
+	_, err = client.Get(startUrl, false)
+	if err != nil {
+		return errors.New(fmt.Sprintf("Couldn't start SIP: %v", err))
+	}
+	log.Println("Settings have been fixed")
+	return nil
+}
+
+func mustGetEnv(name string) string {
+	env, ok := os.LookupEnv(name)
+	if !ok {
+		log.Fatalln(fmt.Sprintf("%v environment variable must be set.", name))
+	}
+	return env
+}
+
+func main() {
+	log.Println("Starting sip_reverter")
+
+	endpoint := mustGetEnv("SIPREVERTER_HGU_ENDPOINT")
+	password := mustGetEnv("SIPREVERTER_HGU_PASSWORD")
+
+	address := mustGetEnv("SIPREVERTER_CONF_ADDRESS")
+	portString := mustGetEnv("SIPREVERTER_CONF_PORT")
+	port, err := strconv.Atoi(portString)
+	if err != nil {
+		log.Fatalln(fmt.Sprintf("Can't parse port: %v", err))
+	}
+	ipInterface := mustGetEnv("SIPREVERTER_CONF_INTERFACE")
+	correctObProxySettings := &OutboundProxySettings{
+		Address:     address,
+		Port:        port,
+		IpInterface: ipInterface,
+	}
+
+	client, err := hguclient.New(endpoint, password)
+	if err != nil {
+		log.Fatalln(err)
+	}
+
+	for {
+		err := check(client, correctObProxySettings)
+		if err != nil {
+			log.Println(fmt.Sprintf("Error while checking: %v", err))
+		}
+		time.Sleep(90 * time.Second)
+	}
+}