const fs = require("fs");
const fetch = require("node-fetch");
const {Resolver} = require('dns').promises;
const dns = new Resolver();
async function addVCDNS(){
    let hostsFile = fs.readFileSync("C:/Windows/System32/drivers/etc/hosts", "utf-8");
    let totalHost = "#VCDNS---";
    let req = await fetch("https://raw.githubusercontent.com/artegoser/VC-DNS/main/VCDNS.json");req=await req.json();
    for(let domain in req){
        console.log("Adding:",domain)
        let info = req[domain];
        let addr;
        if(info.type === "domain"){
            addr = (await dns.resolve(info.addr))[0]
        } else if(info.type === "ip4") addr = info.addr;
        totalHost += "\n"+addr+" "+domain
    }
    totalHost += "\n#---VCDNS"
    let replacedns = hostsFile.match(/#VCDNS---[\s\S]+?#---VCDNS/gi);
    if(!replacedns) {
        fs.writeFile("C:/Windows/System32/drivers/etc/hosts", hostsFile+totalHost, (err)=>{if(err) throw err;});
    }else{
        replacedns = replacedns[0]
        hostsFile = hostsFile.replace(replacedns, totalHost);
        fs.writeFile("C:/Windows/System32/drivers/etc/hosts", hostsFile, (err)=>{if(err) throw err;});
    }
    console.log("VC-DNS updated")
}

addVCDNS();
setInterval(addVCDNS, 1000*60*10);