2018-07-31 17:54:16 +08:00
|
|
|
package config
|
|
|
|
|
|
|
|
import (
|
2018-11-21 13:47:46 +08:00
|
|
|
"fmt"
|
2022-03-15 22:25:33 +08:00
|
|
|
"github.com/Dreamacro/clash/component/geodata"
|
2018-07-31 17:54:16 +08:00
|
|
|
"os"
|
|
|
|
|
|
|
|
C "github.com/Dreamacro/clash/constant"
|
2019-12-20 17:22:24 +08:00
|
|
|
"github.com/Dreamacro/clash/log"
|
2018-07-31 17:54:16 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
// Init prepare necessary files
|
2018-11-21 13:47:46 +08:00
|
|
|
func Init(dir string) error {
|
2018-10-14 21:22:58 +08:00
|
|
|
// initial homedir
|
2018-11-21 13:47:46 +08:00
|
|
|
if _, err := os.Stat(dir); os.IsNotExist(err) {
|
2021-10-10 23:44:09 +08:00
|
|
|
if err := os.MkdirAll(dir, 0o777); err != nil {
|
2020-08-25 22:19:59 +08:00
|
|
|
return fmt.Errorf("can't create config directory %s: %s", dir, err.Error())
|
2018-10-14 21:22:58 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-06-18 20:55:26 +08:00
|
|
|
// initial config.yaml
|
2018-10-14 21:22:58 +08:00
|
|
|
if _, err := os.Stat(C.Path.Config()); os.IsNotExist(err) {
|
2020-02-18 13:48:15 +08:00
|
|
|
log.Infoln("Can't find config, create a initial config file")
|
2021-10-10 23:44:09 +08:00
|
|
|
f, err := os.OpenFile(C.Path.Config(), os.O_CREATE|os.O_WRONLY, 0o644)
|
2020-02-18 13:48:15 +08:00
|
|
|
if err != nil {
|
2020-08-25 22:19:59 +08:00
|
|
|
return fmt.Errorf("can't create file %s: %s", C.Path.Config(), err.Error())
|
2020-02-18 13:48:15 +08:00
|
|
|
}
|
2021-04-01 15:35:33 +08:00
|
|
|
f.Write([]byte(`mixed-port: 7890`))
|
2020-02-18 13:48:15 +08:00
|
|
|
f.Close()
|
2018-07-31 17:54:16 +08:00
|
|
|
}
|
2022-03-16 21:47:00 +08:00
|
|
|
buf, _ := os.ReadFile(C.Path.Config())
|
|
|
|
rawCfg, err := UnmarshalRawConfig(buf)
|
|
|
|
if err != nil {
|
|
|
|
log.Errorln(err.Error())
|
|
|
|
fmt.Printf("configuration file %s test failed\n", C.Path.Config())
|
|
|
|
os.Exit(1)
|
|
|
|
}
|
|
|
|
if !C.GeodataMode {
|
|
|
|
C.GeodataMode = rawCfg.GeodataMode
|
|
|
|
}
|
2022-05-27 12:16:04 +08:00
|
|
|
C.GeoIpUrl = rawCfg.GeoXUrl.GeoIp
|
|
|
|
C.GeoSiteUrl = rawCfg.GeoXUrl.GeoSite
|
|
|
|
C.MmdbUrl = rawCfg.GeoXUrl.Mmdb
|
2022-01-26 12:01:14 +08:00
|
|
|
// initial GeoIP
|
2023-01-09 21:07:31 +08:00
|
|
|
if err := geodata.InitGeoIP(); err != nil {
|
2022-01-26 12:01:14 +08:00
|
|
|
return fmt.Errorf("can't initial GeoIP: %w", err)
|
2018-07-31 17:54:16 +08:00
|
|
|
}
|
2021-11-17 16:03:47 +08:00
|
|
|
|
2018-11-21 13:47:46 +08:00
|
|
|
return nil
|
2018-07-31 17:54:16 +08:00
|
|
|
}
|