package main

import (
	"RuleIniter/common"
	"RuleIniter/conf"
	"encoding/json"
	"flag"
	"fmt"
	"log"
	"os"

	"github.com/InazumaV/V2bX/common/json5"
)

var v2bXConfigPath = flag.String("v2bxPath", "/etc/V2bX/config.json", "V2bX config path")

type V2bXConfig struct {
	Cores []interface{}   `json:"Cores"`
	Log   json.RawMessage `json:"Log"`
	Nodes json.RawMessage `json:"Nodes"`
}

func changeRouteAndOutboundPath() error {
	c := conf.New(*path)
	err := c.LoadConfig()
	if err != nil {
		return fmt.Errorf("load config error: %w", err)
	}
	f, err := os.OpenFile(*v2bXConfigPath, os.O_RDWR, 0744)
	if err != nil {
		return err
	}
	defer f.Close()
	var config V2bXConfig
	err = json.NewDecoder(json5.NewTrimNodeReader(f)).Decode(&config)
	if err != nil {
		return err
	}

	for _, co := range config.Cores {
		coV := co.(map[string]interface{})
		if v, ok := coV["Type"].(string); ok {
			if v != "xray" {
				continue
			}
		} else {
			continue
		}
		if c.Parser.EnableRoute {
			coV["RouteConfigPath"] = c.Parser.RoutePath
			coV["OutboundConfigPath"] = c.Parser.Outbound.LocalOutboundPath
		}
		if c.Parser.EnableDns {
			coV["DnsConfigPath"] = c.Parser.DnsPath
		}
	}
	f.Truncate(0)
	f.Seek(0, 0)
	e := json.NewEncoder(f)

	e.SetIndent("", "    ")
	err = e.Encode(&config)
	if err != nil {
		return err
	}
	return nil
}

func Install() {
	err := changeRouteAndOutboundPath()
	if err != nil {
		log.Fatalln("change v2bx config error:", err)
	}
	err = os.Rename(os.Args[0], "/bin/ruler")
	if err != nil {
		log.Fatalln("move error:", err)
	}
	cmd := fmt.Sprintf(
		"\"%s\" -conf \"%s\"",
		"/bin/ruler",
		*path,
	)
	err = common.AddCronCommand("0 6 * * *", cmd)
	if err != nil {
		log.Fatalln("add crontab task error:", err)
	}
}
