87 lines
1.9 KiB
Go
87 lines
1.9 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"log"
|
|
"os"
|
|
"strings"
|
|
"time"
|
|
|
|
"gitea.urkob.com/urko/go-wifi-switcher/cfg"
|
|
"gitea.urkob.com/urko/go-wifi-switcher/internal/switcher"
|
|
pkgswitcher "gitea.urkob.com/urko/go-wifi-switcher/pkg/switcher"
|
|
"github.com/go-rod/rod/lib/launcher"
|
|
"github.com/go-rod/rod/lib/utils"
|
|
"github.com/ysmood/leakless"
|
|
)
|
|
|
|
var sw pkgswitcher.SwitcherIface
|
|
|
|
func main() {
|
|
envFile := ""
|
|
if os.Getenv("ENV") != "prod" {
|
|
envFile = "./.env"
|
|
}
|
|
|
|
config := cfg.NewConfig(envFile)
|
|
log.SetFlags(log.Lmicroseconds)
|
|
config.LogFile = false
|
|
if config.LogFile {
|
|
logFileName := fmt.Sprintf("%s.txt", time.Now().Format(strings.ReplaceAll(time.RFC1123Z, ":", "_")))
|
|
f, err := os.OpenFile(logFileName, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0o644)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
defer f.Close()
|
|
log.SetOutput(f)
|
|
}
|
|
|
|
var lc *launcher.Launcher
|
|
var remoteControlBrowserURL string
|
|
|
|
if config.Bin != "" {
|
|
lc = launcher.New().Bin(config.Bin)
|
|
remoteControlBrowserURL = lc.MustLaunch()
|
|
log.Println("u = lc.MustLaunch()", remoteControlBrowserURL)
|
|
} else {
|
|
lc = launcher.New()
|
|
path := launcher.NewBrowser().MustGet()
|
|
args := lc.FormatArgs()
|
|
|
|
cmd := leakless.New().Command(path, args...)
|
|
|
|
parser := launcher.NewURLParser()
|
|
cmd.Stderr = parser
|
|
utils.E(cmd.Start())
|
|
remoteControlBrowserURL = launcher.MustResolveURL(<-parser.URL)
|
|
}
|
|
|
|
sw = switcher.NewSwitcher(remoteControlBrowserURL, config)
|
|
if err := sw.SwitchWIFI(); err != nil {
|
|
log.Println("sw.SwitchWIFI", err)
|
|
err := retry(5, time.Second*5, sw.SwitchWIFI)
|
|
if err != nil {
|
|
log.Fatalln("couldn't retry:", err)
|
|
}
|
|
}
|
|
|
|
log.Println("task completed")
|
|
}
|
|
|
|
func retry(attempts int, sleep time.Duration, f func() error) error {
|
|
var err error
|
|
for i := 0; i < attempts; i++ {
|
|
if i > 0 {
|
|
log.Println("retrying after error:", err)
|
|
time.Sleep(sleep)
|
|
sleep *= 2
|
|
}
|
|
err = f()
|
|
if err == nil {
|
|
return nil
|
|
}
|
|
}
|
|
return fmt.Errorf("after %d attempts, last error: %s", attempts, err)
|
|
}
|