2020-08-25 19:38:50 -04:00
|
|
|
package storage
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"fmt"
|
|
|
|
|
"reflect"
|
|
|
|
|
|
|
|
|
|
"github.com/qdm12/gluetun/internal/models"
|
|
|
|
|
)
|
|
|
|
|
|
2022-05-27 00:59:47 +00:00
|
|
|
func countServers(allServers models.AllServers) (count int) {
|
|
|
|
|
for _, servers := range allServers.ProviderToServers {
|
|
|
|
|
count += len(servers.Servers)
|
|
|
|
|
}
|
|
|
|
|
return count
|
2020-08-25 19:38:50 -04:00
|
|
|
}
|
|
|
|
|
|
2021-08-27 19:10:03 +00:00
|
|
|
func (s *Storage) SyncServers() (err error) {
|
2021-09-30 15:22:57 +00:00
|
|
|
serversOnFile, err := s.readFromFile(s.filepath, s.hardcodedServers)
|
2020-12-29 17:49:38 +00:00
|
|
|
if err != nil {
|
2022-02-20 02:58:16 +00:00
|
|
|
return fmt.Errorf("cannot read servers from file: %w", err)
|
2020-08-25 19:38:50 -04:00
|
|
|
}
|
|
|
|
|
|
2021-08-27 19:10:03 +00:00
|
|
|
hardcodedCount := countServers(s.hardcodedServers)
|
2020-12-29 17:49:38 +00:00
|
|
|
countOnFile := countServers(serversOnFile)
|
|
|
|
|
|
|
|
|
|
if countOnFile == 0 {
|
2021-08-27 19:10:03 +00:00
|
|
|
s.logger.Info(fmt.Sprintf(
|
|
|
|
|
"creating %s with %d hardcoded servers",
|
|
|
|
|
s.filepath, hardcodedCount))
|
|
|
|
|
s.mergedServers = s.hardcodedServers
|
2020-12-29 17:49:38 +00:00
|
|
|
} else {
|
2021-08-27 19:10:03 +00:00
|
|
|
s.logger.Info(fmt.Sprintf(
|
|
|
|
|
"merging by most recent %d hardcoded servers and %d servers read from %s",
|
|
|
|
|
hardcodedCount, countOnFile, s.filepath))
|
2020-12-29 17:49:38 +00:00
|
|
|
|
2021-08-27 19:10:03 +00:00
|
|
|
s.mergedServers = s.mergeServers(s.hardcodedServers, serversOnFile)
|
2020-12-29 17:49:38 +00:00
|
|
|
}
|
2020-08-25 19:38:50 -04:00
|
|
|
|
2021-08-27 19:10:03 +00:00
|
|
|
// Eventually write file
|
|
|
|
|
if s.filepath == "" || reflect.DeepEqual(serversOnFile, s.mergedServers) {
|
|
|
|
|
return nil
|
2021-05-06 21:10:28 +00:00
|
|
|
}
|
|
|
|
|
|
2022-05-27 00:59:47 +00:00
|
|
|
if err := flushToFile(s.filepath, &s.mergedServers); err != nil {
|
2022-02-20 02:58:16 +00:00
|
|
|
return fmt.Errorf("cannot write servers to file: %w", err)
|
2020-12-29 00:55:31 +00:00
|
|
|
}
|
2021-08-27 19:10:03 +00:00
|
|
|
return nil
|
2020-08-25 19:38:50 -04:00
|
|
|
}
|