Add workaround for Syncthing apikey setting.
authorSebastien Douheret <sebastien.douheret@iot.bzh>
Fri, 23 Jun 2017 14:55:54 +0000 (16:55 +0200)
committerSebastien Douheret <sebastien.douheret@iot.bzh>
Fri, 23 Jun 2017 16:03:58 +0000 (18:03 +0200)
lib/syncthing/st.go

index 5976e2f..8fd50d3 100644 (file)
@@ -169,13 +169,45 @@ func (s *SyncThing) Start() (*exec.Cmd, error) {
 
        env := []string{
                "STNODEFAULTFOLDER=1",
+               "STNOUPGRADE=1",
+               "STNORESTART=1",
+       }
+
+       // XXX - temporary hack because -gui-apikey seems to correctly handle by
+       // syncthing the early first time
+       stConfigFile := filepath.Join(s.Home, "config.xml")
+       if s.APIKey != "" && !common.Exists(stConfigFile) {
+               s.log.Infof("Stop and restart Syncthing (hack for apikey setting)")
+               s.STCmd, err = s.startProc("syncthing", args, env, &s.exitSTChan)
+               tmo := 20
+               for ; tmo > 0; tmo-- {
+                       s.log.Debugf("Waiting Syncthing config.xml creation (%v)\n", tmo)
+                       time.Sleep(500 * time.Millisecond)
+                       if common.Exists(stConfigFile) {
+                               break
+       }
+               }
+               if tmo <= 0 {
+                       return nil, fmt.Errorf("Cannot start Syncthing for config file creation")
+               }
+               s.Stop()
+               read, err := ioutil.ReadFile(stConfigFile)
+               if err != nil {
+                       return nil, fmt.Errorf("Cannot read Syncthing config file for apikey setting")
+               }
+               re := regexp.MustCompile(`<apikey>.*</apikey>`)
+               newContents := re.ReplaceAllString(string(read), "<apikey>"+s.APIKey+"</apikey>")
+               err = ioutil.WriteFile(stConfigFile, []byte(newContents), 0)
+               if err != nil {
+                       return nil, fmt.Errorf("Cannot write Syncthing config file to set apikey")
+               }
        }
 
        s.STCmd, err = s.startProc("syncthing", args, env, &s.exitSTChan)
 
        // Use autogenerated apikey if not set by config.json
        if s.APIKey == "" {
-               if fd, err := os.Open(filepath.Join(s.Home, "config.xml")); err == nil {
+               if fd, err := os.Open(stConfigFile); err == nil {
                        defer fd.Close()
                        if b, err := ioutil.ReadAll(fd); err == nil {
                                re := regexp.MustCompile("<apikey>(.*)</apikey>")